C ++从DLL加载函数到Boost函数

时间:2011-08-26 11:46:20

标签: c++ dll boost-function

我想从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

谢谢, 戈库尔。

1 个答案:

答案 0 :(得分:4)

您需要注意names mangling and calling convention

所以,在你的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;
}

我确信这个例子可以构建并运行良好。