从动态加载的dll内部调用C ++函数

问题描述 投票:0回答:1

我正在编写一个C ++程序,该程序在运行时动态加载dll并在该dll中调用一个函数。没问题,但是现在我想从dll中调用在C ++程序中定义的函数。

我的main.cpp看起来像这样:

#include <Windows.h>
#include <iostream>

typedef void(*callC)(int);

int main()
{
    HINSTANCE dllHandle = LoadLibrary("D:\Libraries\lib.dll");

    callC func = (callC)GetProcAddress(dllHandle, "callC");

    func(42);

    FreeLibrary(dllHandle);
}

// I want to call this function from my dll
void callableFromDll(){
}

被访问的dll的一部分在C中写成,如下所示:

#include <stdio.h>

void callC(int);

void callC(int i){
    print(i);

    // Call the C++ function
    //callableFromDll();
}

我已经读过__declspec(dllimport)__declspec(dllexport)属性,但是对于C ++来说真的很新,不知道这些是否是正确的用法,如果是,如何使用它们。

c++ c dll declspec
1个回答
2
投票

在您的C ++程序中:

extern "C" _declspec(dllexport) void callableFromDll(int value) {
    printf("This function was called from the main process. Value: %d\n", value);
}

在您的DLL中:

typedef void(*callableFromDll)(int);
callableFromDll func;

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        func = (callableFromDll)GetProcAddress(GetModuleHandle(NULL), "callableFromDll");
        func(69);
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:

        break;
    }
    return TRUE;
}
GetModuleHandle(NULL)

返回父级的可执行句柄。

当LoadLibrary加载DLL时从exe控制台输出:

DLL_PROCESS_ATTACH
This function was called from the main process. Value: 69

cppfunction.exe (process 16336) exited with code 0.
Press any key to close this window . . .

extern "C"告诉编译器不要将函数的名称编码为唯一的名称。编译器对名称进行编码,以便链接器可以分隔通用函数或变量名称。

请参见extern "C" and extern "C++" function declarationsExporting from a DLL Using __declspec(dllexport) Importing function calls using __declspec(dllimport)

© www.soinside.com 2019 - 2024. All rights reserved.