Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1696595
  • 博文数量: 263
  • 博客积分: 1218
  • 博客等级: 少尉
  • 技术积分: 2862
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-19 02:33
文章分类

全部博文(263)

文章存档

2020年(12)

2019年(2)

2018年(10)

2016年(1)

2015年(20)

2014年(115)

2013年(46)

2012年(37)

2011年(20)

分类: C/C++

2014-04-25 17:19:08

这个问题很有意思,我之前还没碰到过呢,我帮你在全球最大的编程论坛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(thisC);
}
bool C_foo( void* thisC, int arg ) {
   return static_cast(thisC)->foo( arg );
}


转:
阅读(1437) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~