extern C return class object
Asked Answered
M

3

9

I want to have a plugin, with a simpler name to resolve in other C++ code.

class B {
};

extern "C" B foo(); // to avoid name mangling in order to be loaded by dlsym

And in the other part of the program (which is also in C++ and shares the same definition of class B with the plugin):

B (*func)();
func = dlsym("/path/to/so", "foo");
B m = func();

Will such code cause any problem, i.e. is it allowed (by standard) to use a C++ class as parameter or return type in an extern "C" function? It seems to work on my gcc, but what about the others?

Microcosm answered 27/1, 2013 at 15:35 Comment(3)
I don't see any problem with your code.Lambdoid
Why is it tagged [C] in addition to [C++]? The question seems to deal with C++ only. And the nature of the question changes drastically if we also have to consider C language.Threatt
Note that dlsym() takes a handle returned from dlopen(), not the pathname of a shared library.Endeavor
C
3

That should work, with a few conditions:

  • If you intend to switch the definition of class B to something else, it won't work. The only thing you can change is the definition of foo().
  • Both the plugin and the loading program must agree on the interface of class B on a binary level. Switching compilers (including version and some flags) can change this interface.
  • You obviously have to cast the returnvalue of dlsym() in C++.
  • Using classes in C is not possible.
Colombo answered 27/1, 2013 at 15:44 Comment(0)
H
3

Declaring foo() as extern "C" will of course allow you to load it through dlsym() using the actual, unmangled function name, but otherwise will have no effect on how you use that function after you load it.

The usual rules still apply. If you break binary compatibility of either foo() or class B, you will need to recompile the plugin, just as you would have to recompile it if it was a regular, non-runtime loaded dynamic library.

Heirship answered 27/1, 2013 at 16:5 Comment(0)
T
1

It will work as long as you are sticking to C++ and only to C++. For obvious reasons you will not be able to compile your function declaration in a C translation unit. (I.e. you will never be able to properly explain to C compiler what B is.)

So, the only issue I see here is what the meaning of [C] tag on your question is. Do you also need some sort of cross-compatibility with C?

Threatt answered 27/1, 2013 at 19:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.