c调用c++对象中的方法

普通调用

https://www.cnblogs.com/Yogurshine/p/3913073.html


https://zhidao.baidu.com/question/531286375.html

这个问题很有意思,我之前还没碰到过呢,我帮你在全球最大的编程论坛stackoverflow上搜了一个答案:
这个答案大意是说,C语言没有this指针,所以要自己写一个wrap API来封装C++的对象。
这个论坛高手云集,包括很多业界大拿,所以这个答案还是很可信的。下面的api.h 就是你要写的wrap API

C has no thiscall notion. The C calling convention doesn't allow directly calling C++ object member functions.
Therefor, you need to supply a wrapper API around your C++ object, one that takes the this pointer explicitly, instead of implicitly.
Example:

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值