如何在“C”代码中调用“C ++”类成员函数?
我有两个文件 .cpp ,其中我定义了一些具有成员函数的类,并对应包含了一些其他帮助cpp / h文件的相应 .h 文件。
现在我想在 C 文件中调用这些CPP文件的功能。我该怎么做?
C语言没有 thiscall
的概念。C调用约定不允许直接调用C++对象的成员函数。
因此,您需要提供一个围绕您的C++对象的包装器API,该API显式地接受this
指针,而不是隐式地传递它。
例如:
// C.hpp
// uses C++ calling convention
class C {
public:
bool foo( int arg );
};
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
你的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 );
}
void*
。因此,对于API中所需的任何类,您都需要一组C包装器函数。当然,您会尝试尽可能保持API尽可能小,这可能会引起一些重新思考... - xtoflvoid*
,你可以为此目的前向声明一个struct
,在 C++ 中为每个类使用不同的struct
。或者更可能是为每个基类在 C++ 中使用不同的struct
,因为 C 无法处理多态性。 - Steve Jessop