2

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

谢谢,戈库尔。

4

1 回答 1

4

您需要注意名称修改和调用约定

因此,在您的 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;
}

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

于 2011-08-26T12:42:20.290 回答