Dynamic Shared Library compilation with g++

情到浓时终转凉″ 提交于 2019-12-02 16:25:08

C allows implicit casts from void * to any pointer type (including function pointers); C++ requires explicit casting. As leiflundgren says, you need to cast the return value of dlsym() to the function pointer type you need.

Many people find C's function pointer syntax awkward. One common pattern is to typedef the function pointer:

typedef double (*cosine_func_ptr)(double);

You can define your function pointer variable cosine as a member of your type:

cosine_func_ptr cosine;

And cast using the type instead of the awkward function pointer syntax:

cosine = (cosine_func_ptr)dlsym(handle, "cos");
leiflundgren

dlsym returns a pointer to the symbol. (As void* to be generic.) In your case you should cast it to a function-pointer.

 double (*mycosine)(double); // declare function pointer
 mycosine = (double (*)(double)) dlsym(handle, "cos"); // cast to function pointer and assign

 double one = mycosine(0.0); // cos(0)

So this one of these rare cases where the compiler error is a good clue. ;)

James Thompson

With the way your code if written, this is really more of a C question, but you can get this to will work in C++. I don't have a tutorial for you on Dynamic Shared Libraries (the web page you linked to seems fine), but here's how to fix your code in C++:

  • declare my_cos to be a function that will (eventually) call the dynamically loaded cosine function:

    double my_cos(double);
    
  • assign the function pointer to my_cos

    my_cos = (double (*)(double)) dlsym(handle, "cos");
    

This is a little complicated, but it's assigning to my_cos something that returns a double, is the result of dereferencing another function pointer, and takes a double as an argument. As other people have posted, C++ is a little more demanding about the explicitness of your code than C.

  • replace that rather dated fputs message with a std::cerr or std::cout:

    std::cerr << "error loading library cos: " << error << std::endl;
    

and

std::cout << "result is " << (*my_cos)(2.0)) << std::endl;

Hope that this help. If that weird casty stuff scares you, I'd recommend Deep C Secrets by van Linden, and definitely the Kernighan and Ritchie Book on C.

Edit: Good point in the comment about how you're specifically looking for a development guide in C++ rather than C to avoid this type of problem. I don't know of a comparable guide in C++, but about 99% of C code can be embedded in C++ code and work just fine. This function pointer case is one of the exceptions.

In C++, you have to perform a reinterpret_cast (not a C cast):

typedef double (* double_from_double_function_t(double));
…
double_from_double_function_t cosine = reinterpret_cast<double_from_double_function_t>(dlsym(handle, "cos"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!