2011-08-26 72 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; 
} 

我敢肯定,這個例子建立並運行良好。