Ajay Brahmakshatriya
Ajay Brahmakshatriya

Reputation: 9203

extern "C" for functions loaded with dlsym

In a C++ project I am loading a .so with dlopen and dlsym. The .so is compiled from C source and all functions have C linkages.

The only part I am not able to figure out is how do I cast the resulting pointer to an extern "C" function so that the actual call site uses the appropriate linkage.

I know one of the main difference is the name mangling and I don't have to worry about that because I am using the unmangled name to find the function with dlsym.

But my understanding is there are other aspects of the linkage which could be a mismatch (I am thinking of exception handling, different ABI?).

I have tried -


extern "C" void (*foo) (void) = (void (*) (void)) dlsym(handle, "foo");

But the compiler doesn't like extern "C" for local variables. What is the right way to call functions loaded with dlsym? Or should I not have to worry about linkages?

Edit: To further clarify the question, I need to compute the function pointer types based on some template parameters which makes this harder and after the discussions in the answers and comments it is currently not possible to do this (the standards are being adjusted to allow this). The current accepted answer correctly answers the question asked.

Upvotes: 2

Views: 666

Answers (1)

Davis Herring
Davis Herring

Reputation: 39818

Introduce a typedef first:

extern "C" typedef void (*verb)();
void f() {
  const auto foo=(verb)dlsym(handle, "foo");
}

Upvotes: 2

Related Questions