static member function with C language binding?

雨燕双飞 提交于 2019-12-04 03:16:41

C++11 7.5/4 "Linkage specifications"

A C language linkage is ignored in determining the language linkage of the names of class members and the function type of class member functions.

So your example is valid in the sense that it's not malformed or an error, but the extern "C" should have no effect on S::foo() or T::foo().

Hellmar Becker

A static member function has the same calling convention as a C function. But, name mangling applies. So, even if you get away with declaring your static member as extern "C", the linker would probably not find it when you try to link it against the C code that calls that function.

What you can easily do is declare a wrapper/stub that calls the static member from a plain function. Also, you can assign the static member function's address to a plain function pointer.

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

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 should be defined in a external C module.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!