Куда мне поместить DLL, сгенерированную в другом проекте из того же решения? Я использую Visual Basic Visual Studio 2017-? - PullRequest
2 голосов
/ 07 октября 2019

Я создал C ++ DLL в Visual Studio 2017, используя следующие источники:

Заголовок: stdfax.h

// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once

#include "targetver.h"

#define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers
// Windows Header Files
#include <windows.h>



// reference additional headers your program requires here

Заголовок: targetver.h

#pragma once

// Including SDKDDKVer.h defines the highest available Windows platform.

// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.

#include <SDKDDKVer.h>

Источник: stdafx.cpp

#include "stdafx.h"

Источник: dll.cpp

// dll.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"

Источник: dllmain.cpp

// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

Источник: Source.cpp <- именно здесь я собираюсь добавить свой исходный файл </p>

#include "stdafx.h"

#define EXPORTING_DLL

int HelloWorld(int A) {
    return (2 * A);
}

Определение: Source.def <- намерение использовать эту DLL из VB .NET </p>

LIBRARY dll

DESCRIPTION 'A C++ dll tat can be called from VB'

EXPORTS
    HelloWorld

Теперь я пытаюсь использовать эту DLL с помощью VBПроект .NET в том же решении:

Imports System.Runtime.InteropServices

Public Class Form1

    <DllImport("dll.dll", CallingConvention:=CallingConvention.Cdecl)>
    Private Shared Function HelloWorld(ByVal x As Int64) As Int64
    End Function

    Private Declare Function HelloWorld Lib "dll.dll" (int) As Integer

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim j

        j = HelloWorld(CInt(TextBox1.Text))
        TextBox2.Text = j

    End Sub
End Class

Но я получаю:

System.DllNotFoundException: 'Unable to load DLL 'dll.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)'

РЕДАКТИРОВАТЬ: После комментария Винсента о возможности этого существадубликат Проблемы с добавлением моей DLL-библиотеки Visual-C ++ в мое приложение графического интерфейса Windows VB.NET Я проверил эту ссылку, и она действительно говорит, как добавить DLL в проект VB. В этом смысле это дубликат, однако, я исправил, что теперь при попытке доступа к DLL я нахожу следующую ошибку:

System.BadImageFormatException: 'An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)'

Я также, после побочного комментария, изменил свой исходный файл, содержащийфункция, которую нужно экспортировать в:

Source: Source.cpp <- это то место, где я собираюсь добавить свой исходный файл </p>

#include "stdafx.h"

#define EXPORTING_DLL

extern "C" int HelloWorld(int A) {
    return (2 * A);
}

Я думаю, чтоУстраняя эту последнюю проблему, этот вопрос может быть полезен для других, поскольку это простой, но задокументированный пример «HelloWorld» о том, как собрать DLL на C ++ и использовать ее в VB.NET.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...