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

我们如何在“C”代码中调用“C ++”类成员函数?

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

现在我想在“C”文件中调用CPP文件的这些function。 我该怎么做?

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

因此,您需要在C ++对象周围提供一个包装器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(thisC); } bool C_foo( void* thisC, int arg ) { return static_cast(thisC)->foo( arg ); } 

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