2011-08-26 91 views
2

我想从DLL加载特定函数并将其存储在Boost函数中。这可能吗?C++将函数从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。

+1

我喜欢你在同一句子中如何使用“执行正常”和“崩溃”;) –

+1

你能确认'func'不是null吗? –

+0

实际上,我的意思是当它被称为fobj()时崩溃,在下一句 – Gokul

回答

4

你需要照顾约names mangling and calling convention

所以,在你的DLL:

// mydll.h 
#pragma comment(linker, "/EXPORT:[email protected]") 
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; 
} 

我敢肯定,这个例子建立并运行良好。