从DLL加载函数到Boost函数

C++ Load function from DLL into Boost function

本文关键字:函数 Boost 加载 DLL      更新时间:2023-10-16

我想从DLL中加载一个特定的函数并将其存储在Boost函数中。这可能吗?

typedef void (*ProcFunc) (void);
typedef boost::function<void (void)> ProcFuncObj;
ACE_SHLIB_HANDLE file_handle = ACE_OS::dlopen("test.dll", 1);
ProcFunc func = (ProcFunc) ACE_OS::dlsym(file_handle, "func1");
ProcFuncObj fobj = func; //This compiles fine and executes fine
func(); //executes fine
fobj(); //but crashes when called

谢谢,Gokul .

您需要注意名称混淆和调用约定:

所以,在你的DLL中:
// mydll.h
#pragma comment(linker, "/EXPORT:fnmydll=_fnmydll@4") 
extern "C" int WINAPI fnmydll(int value);
// mydll.cpp
#include "mydll.h"
extern "C" int WINAPI fnmydll(int value)
{
    return value;
}

然后,在您的DLL客户端应用程序中:

#include <windows.h>
#include <boost/function.hpp>
#include <iostream>
int main()
{
    HMODULE dll = ::LoadLibrary(L"mydll.dll");
    typedef int (WINAPI *fnmydll)(int);
    // example using conventional function pointer
    fnmydll f1 = (fnmydll)::GetProcAddress(dll, "fnmydll");
    std::cout << "fnmydll says: " << f1(3) << std::endl;
    // example using Boost.Function
    boost::function<int (int)> f2 = (fnmydll)::GetProcAddress(dll, "fnmydll");
    std::cout << "fnmydll says: " << f2(7) << std::endl;
    return 0;
}

我确信这个例子构建和运行良好。

相关文章: