Function pointer call doesn't compile

若如初见. 提交于 2019-12-24 11:26:36

问题


I just dont get it, why line 22 is failing to compile?

#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;
    }
}

Any help is welcome If you need additional information's just let me know.


回答1:


I take it that fuPtr points to a function that is supposed to return a pointer to a Library object (given the name loaded is "createLibrary").

In that case, the line including your cast needs to look like this:

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



回答2:


invalid static_cast from type ‘void*’ to type ‘Library*()’

In C++ it is illegal to cast between object and function pointer types (because e.g. they could be of different size).

Most compilers that support this as an extension will require you to use a reinterpret_cast or even a c-style cast.




回答3:


"Library* ()" does not evaluate to a type. Try "Library * (*)()"



来源:https://stackoverflow.com/questions/8245880/function-pointer-call-doesnt-compile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!