【问题标题】:Bind function pointer to boost::function object将函数指针绑定到 boost::function 对象
【发布时间】:2011-12-02 15:33:17
【问题描述】:

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

元代码

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

...

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

Library* libInstance = functionObj();

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

【问题讨论】:

    标签: c++ function-pointers boost-bind boost-function function-object


    【解决方案1】:

    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();
    

    【讨论】:

    • 有独立于平台的方法吗?
    • @Mythli:不。就像我说的,将void* 转换为函数指针取决于平台。如果您可以访问GetFunction 中的真实函数指针,则可以将其重构为模板并避免使用void*,从而跳过所有特定于平台的麻烦。
    • 很抱歉没有直接接受你的回答,但是我很长时间不在家,所以无法测试。
    • @Mythli 嘿,不用道歉。我很高兴它有所帮助。
    【解决方案2】:

    使用 boost::bind,您可以将函数真正绑定到 boost 函数对象。

    boost::function</*proper function pointer type*/> functionObj = boost::bind(functionPtr); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多