函数指针调用不编译

Function pointer call doesn't compile

本文关键字:编译 调用 指针 函数      更新时间:2023-10-16

我只是不明白,为什么第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;
    }
}

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

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

在这种情况下,包括强制转换在内的行需要看起来像这样:

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

从' void* '类型转换为' Library*() '类型无效

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

大多数支持此扩展的编译器将要求您使用reinterpret_cast甚至c风格的强制转换。

"Library*()"不计算为类型。试试"Library * (*)()"