我无法创建返回unique_ptr的函数的函数指针

时间:2019-02-28 20:49:51

标签: c++ function-pointers

我想在运行时从动态库中调用一个函数。该函数返回一个指向动态分配对象的指针(我将下面的代码简化为一个int)。
我想在下面的代码中将此指针存储到该对象,以根据需要使用该对象。

#include <dlfcn.h>
#include <memory>

/* myFunction() is supposed to be in my dynamic library */
std::unique_ptr<int> myFunction()
{
    return std::unique_ptr<int>(new(int));
}

int main(int argc, char *argv[])
{
    int *(*functionPtr)() = nullptr;

    void *handle = dlopen(argv[1], RTLD_NOW);
    int *symbolAddress = static_cast<int *>(dlsym(handle, "myFunction"));

    *(int **)(&functionPtr) = symbolAddress;

    int *x = functionPtr();
    //std::unique_ptr<int> x = functionPtr();

    return 0;
}

上面的代码可以编译,但是我写道,函数myFunction的返回类型是“ int *”(在主函数中),而在我的库中的函数声明中不是这种情况。

PS:在我的示例中,为简化起见,我将“对象”的类型称为“ int”。
我的最终目标是取消最后一行的注释。

我可能做错了事。我仍在学习语言,但我想正确编码,因此我愿意重组我的代码。

1 个答案:

答案 0 :(得分:2)

myFunction的类型为std::unique_ptr<int> ()。因此,指向myFunction的指针的类型为std::unique_ptr<int> (*)()。正是应该这样声明functionPtr

std::unique_ptr<int> (*functionPtr)();

另外:

*(int **)(&functionPtr) = symbolAddress;

这种类型打孔的写法在C和C ++中都违反了严格的别名,因此我不确定为什么symbolAddressint *的原因。您的代码可能看起来应该像这样:

void *symbolAddress = dlsym(handle, "myFunction");
functionPtr = (std::unique_ptr<int>(*)())symbolAddress;
相关问题