gpt4 book ai didi

C++ 将 DLL 中的函数加载到 Boost 函数中

转载 作者:搜寻专家 更新时间:2023-10-31 01:18:21 25 4
gpt4 key购买 nike

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

谢谢,悟空。

最佳答案

你需要注意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;
}

我确信这个示例构建并运行良好。

关于C++ 将 DLL 中的函数加载到 Boost 函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7204173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com