Static member function with C language binding?

The following C ++ code compiles with Visual C ++ and g ++:

struct S { static void foo(); }; extern "C" void S::foo() {} struct T { static void foo(); }; extern "C" void T::foo() {} auto main() -> int { S().foo(); T().foo(); } 
  • Is it really?

  • If it is valid, since the implementation can be in a separate translation unit, does this mean that the static member function always has the same calling convention as the C function (and if not, how does this not mean that)?

+8
c ++ c member-functions
source share
3 answers

C ++ 11 7.5 / 4 "Communication Characteristics"

C language bindings are ignored when defining language bindings; the names of class members and the type of function of a member of a class of a function.

So your example is valid in the sense that it is not distorted or has an error, but extern "C" should not affect S::foo() or T::foo() .

+8
source share

A static member function has the same calling convention as a C function. But, the name mangling is used. That way, even if you manage to declare your static member as extern "C" , the linker will probably not find it when you try to associate it with the C code that calls this function.

What you can easily do is declare a wrapper / stub that calls the static member from a simple function. In addition, you can assign a static address to a function-function to a pointer to a simple function.

+4
source share

No, this is ignored, the problem is related to the name mangling (function assignment for the binding phase). So the trick is to define a C function and use your static C ++ method as a stub to call it, for example:

 struct S { static void foo(); }; extern "C" void S_foo_impl(); void S::foo() { S_foo_impl(); } auto main() -> int { S::foo(); } 

Of course, S_foo_impl must be defined in the external module C.

0
source share

All Articles