调用" C ++"类的成员函数从" C" code [英] Calling "C++" class member function from "C" code

查看:165
本文介绍了调用" C ++"类的成员函数从" C" code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何可以调用CC ++类的成员函数code?

How can we call "C++" class member functions in 'C" code ?

我的的.cpp,在我与其中包括了一些其他的帮助CPP / h的文件,成员函数和相应的的.h头文件中定义的一些类两个文件。

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文件中的C文件中的这些功能​​。
我该怎么办呢?

Now I want to call these functionality of CPP files in "C" file. How can I do it?

推荐答案

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 );
}

有很多伟大的文档在那里了。第一个<一href=\"http://www.google.be/search?sourceid=chrome&ie=UTF-8&q=wrapping+C%2B%2B+object+into+C\">I碰到可以在这里找到

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

这篇关于调用&QUOT; C ++&QUOT;类的成员函数从&QUOT; C&QUOT; code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆