Home > Back-end >  Are only C defined data types allowed during an extern "C" within C ?
Are only C defined data types allowed during an extern "C" within C ?

Time:05-28

I'm working on a dynamic library, is it possible to have a function output a custom class object when using extern "C" or am I limited to data types native to C.

For example, could I have

extern "C" std::string func(const std::string& str);

So that I can get that function and use it after loading the library and getting the function symbol?

std::string result = func("Lol");

CodePudding user response:

extern "C" std::string func(const std::string& str);

will give func C-style linkage. func will not be mangled to allow for fun C tricks like overloading.

It won't prevent the function from accepting or returning a C type, but the calling language will have to know how to interpret the type. For types that are not Standard layout, trivial types (what we used to call POD) this will be difficult-to-impossible.

Side note: Since Standard Library implementations can differ, this can be problematic for a type like std::string even if the caller is C code.

CodePudding user response:

From the standard:

Linkage from C to objects defined in other languages and to objects defined in C from other languages is implementation-defined and language-dependent. Only where the object layout strategies of two language implementations are similar enough can such linkage be achieved.

In the context of your question, I interpret this to mean: Yes, you can use C linkage (to skip mangling/simplify symbol names) on C -specific objects and types, but the environment referencing those symbols needs to be specified such that it can make sense of those objects. As your linking environment is also C , this should not be a problem, assuming you use binary-compatible versions of the C standard library/STL on "both sides".

  •  Tags:  
  • c
  • Related