简体   繁体   English

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

[英]Calling “C++” class member function from “C” code

How can we call "C++" class member functions in 'C" code ? 我们如何在“ C”代码中调用“ C ++”类成员函数?

I have two files .cpp, in which I have defined some classes with member functions and corresponding " .h" files which has included some other helping cpp/h files. 我有两个.cpp文件,其中我定义了一些带有成员函数的类以及相应的“ .h”文件,其中包括一些其他帮助cpp / h文件。

Now I want to call these functionality of CPP files in "C" file. 现在,我要在“ C”文件中调用CPP文件的这些功能。 How can I do it? 我该怎么做?

C has no thiscall notion. C没有thiscall概念。 The C calling convention doesn't allow directly calling C++ object member functions. C调用约定不允许直接调用C ++对象成员函数。

Therefor, you need to supply a wrapper API around your C++ object, one that takes the this pointer explicitly, instead of implicitly. 因此,您需要为C ++对象提供一个包装器API,该包装器显式而不是隐式地使用this指针。

Example: 例:

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

C wrapper API: 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

Your API would be implemented in C++: 您的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 );
}

There is a lot of great documentation out there, too. 也有很多很棒的文档。 The first one I bumped into can be found here . 我碰到的第一个可以在这里找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM