c++ccalling-conventionfunction-templatesextern-c

How do you call a templated C++ free function from C?


I want to pass the pointer of an instance of a function template to a C function as callback. It's obviously impossible to declare the template as extern "C".

Is it guaranteed that C++ uses the same calling convention with C for nonmember function? And is there any other effect of declaring a function in extern "C" besides it prevents incompatible name mangling?


Solution

  • No. It's not guaranteed that it uses the same calling convention. You can use the calling convention modifiers like _stdcall, cdecl, pascal, etc. So you have to make sure that both sides know the same calling convention.

    One way would be detecting the mangled name and define a proper prototype for the C function.

    Consider changing the design; since you can't benefit from the template in C anyway, you can define a simple C++ function (defined extern "C") that calls the templated function.