从"C"代码调用"C++"类成员函数

Pri*_*shu 16 c c++

如何在"C"代码中调用"C++"类成员函数?

我有两个文件.cpp,其中我已经定义了一些带有成员函数的类和相应的" .h"文件,其中包含了一些其他帮助cpp/h文件.

现在我想在"C"文件中调用CPP文件的这些功能.我该怎么做?

xto*_*ofl 34

C没有thiscall概念.C调用约定不允许直接调用C++对象成员函数.

因此,您需要在C++对象周围提供一个包装器API,它可以this显式地而不是隐式地获取指针.

例:

// C.hpp
// uses C++ calling convention
class C {
public:
   bool foo( int arg );
};
Run Code Online (Sandbox Code Playgroud)

C包装API:

// api.h
// uses C calling convention
#ifdef __cplusplus
extern "C" {
#endif

void* C_Create();
void C_Destroy( void* thisC );
bool C_foo( void* thisC, int arg );

#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)

您的API将在C++中实现:

#include "api.h"
#include "C.hpp"

void* C_Create() { return new C(); }
void C_Destroy( void* thisC ) {
   delete static_cast<C*>(thisC);
}
bool C_foo( void* thisC, int arg ) {
   return static_cast<C*>(thisC)->foo( arg );
}
Run Code Online (Sandbox Code Playgroud)

那里也有很多很棒的文档.我碰到的第一个可以在这里找到.

  • @Priyanshu:任何来自C++的指针对象都需要在API函数中被翻译为`void*`.因此,对于API中您需要的任何类,您将需要一组C包装器函数.当然,你试图让API尽可能小,这可能会引起一些反思...... (2认同)
  • @xtofl:不一定是“ void *”,您可以为此目的向前声明一个“ struct”,对C ++中的每个类使用不同的“ struct”。或更可能是C ++中的每个基类,因为C无法处理多态性。 (2认同)