【问题标题】:Function pointer call doesn't compile函数指针调用无法编译
【发布时间】:2012-01-04 23:06:36
【问题描述】:

我就是不明白,为什么第 22 行编译失败?

#include <stdexcept>
#include <dlfcn.h>
#include "Library.h"

int main(int argc, char *argv[])
{
    try
    {
        void* libHandle = 0;

        libHandle = dlopen("libExpandableTestLibrary.so", RTLD_LAZY);
        if(!libHandle)
            throw std::logic_error(dlerror());

        std::cout << "Libary opened gracefully" << std::endl;

        void* fuPtr = 0;
        fuPtr = dlsym(libHandle, "createLibrary");
        if(!fuPtr)
                throw std::logic_error(dlerror());

        Library* libInstance = static_cast<Library* ()>(fuPtr)();
        // Tutorial: http://www.linuxjournal.com/article/3687
        // Tutorial Code: shape *my_shape = static_cast<shape *()>(mkr)();
        // Compiler error message:  Application.cpp:22:56: error: invalid static_cast from type ‘void*’ to type ‘Library*()’
        libInstance->Foo();

        dlclose(libHandle);

    } catch(std::exception& ex)
    {
        std::cerr << ex.what() << std::endl;
    }
}

欢迎任何帮助 如果您需要更多信息,请告诉我。

【问题讨论】:

  • 试试reinterpret_cast - void* 和其他演员不要混用。
  • @JohnDibling,它内嵌在代码中...
  • @Nim:不完全是。从void* 转换为任何其他对象指针类型(可能以前隐式转换为void*)正确的方法是static_cast
  • @PlasmaHH,可能有一个对象指针,但也有一个函数指针?
  • 对于想要创建动态类加载代码的人,请查看这个单头库:github.com/davidalbertonogueira/…@Disclaimer:我是上述库的维护者。

标签: c++ shared-libraries function-pointers


【解决方案1】:

我认为fuPtr 指向一个函数,该函数应该返回指向Library 对象的指针(假设加载的名称是"createLibrary")。

在这种情况下,包含您的演员的行需要如下所示:

Library* libInstance = reinterpret_cast<Library* (*)()>(fuPtr)();

【讨论】:

  • 这也不起作用,因为在这种情况下您必须使用 reinterpret_cast 但是,您向我指出了正确的解决方案。提前致谢。解决方案:Library* libInstance = reinterpret_cast(fuPtr)();
  • 啊。由于没有方便的库,我插入了一个测试函数,我的编译器对static_casting 没有任何抱怨。但重点。
【解决方案2】:

从“void*”类型到“Library*()”类型的无效静态转换

在 C++ 中,在对象和函数指针类型之间进行强制转换是非法的(因为它们可能具有不同的大小)。

大多数支持此作为扩展的编译器将要求您使用 reinterpret_cast 甚至 c 样式转换。

【讨论】:

  • static_cast() 需要一个类型作为参数。提供的类型根本不是类型。
  • @bert-jan:它是一个类型,试试下面的代码:struct L; L*f(); 它不是函数指针类型,而是函数类型。另请参阅std::function&lt;L*()&gt; f; 等模板参数。由于任何这种类型的转换都是编译器扩展,它是否会自动衰减为指向函数的指针(就像真正的函数一样)取决于他们。取决于他的编译器如何实现这样的扩展,使其成为指向函数的指针可能是必要的,也可能不是。
【解决方案3】:

"Library* ()" 不计算类型。试试“库 * (*)()”

【讨论】:

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