如何在"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)