且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

调用" C ++"类的成员函数从" C" code

更新时间:2021-08-01 08:32:13

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

C has no thiscall notion. The C calling convention doesn't allow directly calling C++ object member functions.

为此,您需要提供一个封装API在你的C ++对象,即需要在这个指针明确,而不是含蓄。

Therefor, you need to supply a wrapper API around your C++ object, one that takes the this pointer explicitly, instead of implicitly.

例如:

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

C包装API:

C wrapper 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 ++中实现:

Your API would be implemented in 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 );
}

有很多伟大的文档在那里了。第一个I碰到可以在这里找到

There is a lot of great documentation out there, too. The first one I bumped into can be found here.