gpt4 book ai didi

c++ - 将函数指针绑定(bind)到 boost::function 对象

转载 作者:太空宇宙 更新时间:2023-11-04 12:14:37 25 4
gpt4 key购买 nike

如何使用原始函数指针初始化 boost::function 对象?

元代码

extern "C"
{
class Library
{
...
};
Library* createLibrary();
}

...

void* functionPtr = library.GetFunction("createLibrary");
boost::function<Library*()> functionObj(functionPtr);

Library* libInstance = functionObj();

如果您需要更多信息,请告诉我。

最佳答案

void* 不是函数指针,因此您不能从中创建 boost::function。您可能想先将其转换为适当的函数指针。如何做到这一点取决于实现。

这就是 POSIX ( rationale ) 中推荐的这种丑陋转换的方式:

void* ptr = /* get it from somewhere */;
Library* (*realFunctionPointer)(); // declare a function pointer variable
*(void **) (&realFunctionPointer) = ptr // hack a void* into that variable

您的平台可能需要不同的技巧。

一旦你有了这样的指针,你就可以简单地做:

boost::function<Library*()> functionObj(realFunctionPtr);

Library* libInstance = functionObj();

关于c++ - 将函数指针绑定(bind)到 boost::function 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8358674/

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