Function pointer call doesn't compile

2019-08-07 10:24发布

问题:

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 * (*)()"