如何在Objective-C中包装C ++库? [英] How to wrap a C++ lib in objective-C?

查看:78
本文介绍了如何在Objective-C中包装C ++库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++库(仅.h),其中包含数据结构的实现,我想在我的iPhone应用程序中使用它.

I have a C++ library (.h only) that contains the implementation of a data structure and I'd like to use it in my iPhone app.

首先,我在Objective-C ++中编写了一个包装器,该包装器通过组合具有C ++类的ivar.然后,我不得不将包装器类扩展名更改为.mm,这看起来还不错.但是然后我必须将此包装的类文件包含到其他几个文件中,因此我也必须更改其扩展名(以防止出现一系列编译时错误).

Firstly, I wrote a wrapper in objective-C++ as a class that, through composition, has an ivar of the C++ class. I then was 'obliged' to change the wrapper class extension to .mm, and it seemed fine. But then I have to include this wrapped class file into several other files, so I have to change their extension too (in order to prevent a wave of compile-time errors).

我正确吗?有没有办法将.mm扩展名限制"到仅几个文件?(从而防止名称冲突等)

Am I correct? Is there a way to 'confine' the .mm extension to just few files?(and so preventing name clashes etc)

一些更多的信息可能会有所帮助,我使用LLVM 1.5作为编译器(我注意到编译时错误的数量从GCC 4.2到LLVM 1.5有所不同,但是我不确定这意味着什么,因为我没有一眼看看所有的东西)

Some more info that might help, I'm using LLVM 1.5 as the compiler (I noticed that the number of compile time errors varies from GCC 4.2 to LLVM 1.5 but I'm not sure that it means much, since I didn't have a look at them all)

推荐答案

我的建议是将C ++位包装在#ifdefs中:

My recommendation is to wrap the C++ bits in #ifdefs:

//MyWrapper.h

#ifdef __cplusplus
class ComposedClass;
#endif 

@interface MyWrapper : NSObject
{
#ifdef __cplusplus
ComposedClass *ptr;
#endif
}

// wrapped methods here...
@end

这是PIMPL惯用语的一个较la脚的版本,但是代码较少,并且对于隐藏纯Objective-C代码中的C ++形式有效.显然,您必须在MyWrapper.mm中包含ComposedClass的标头.

This is a slightly lame version of the PIMPL idiom, but less code, and effective for hiding C++-isms from your pure Objective-C code. Obvioulsy you would have to include the ComposedClass's header in your MyWrapper.mm.

如果ComposedClass是模板类型,则需要将第一个块修改为

If ComposedClass is a templated type, you will need to modify the first block to

#ifdef __cplusplus
#include "ComposedClass.h"
#endif

而不是使用前向声明,然后当然在Objective-C类的实例变量声明中使用模板化类型.

instead of using a forward declaration and then, of course, use the templated type in your Objective-C class' instance variable declaration.

此方法为 查看全文

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