为C ++库创建一个Objective-C包装器 [英] Making a Objective-C Wrapper for a C++ Library

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

问题描述

我想在Objective-C中创建一个包装,所以我不必在库类之外编写c ++。

I am trying to make a wrapper in Objective-C so I don't have to write c++ outside the library classes.

库主文件是 LLAHProcessor.h .cpp

我的包装器是 LLAHProcessorWrapper.h .mm

它编译正常,但当我将 LLAHProcessorWrapper 添加到其他类一个成员变量我得到了几百个错误,如:

It compiles fine, but when I add LLAHProcessorWrapper to other class, (Lets say an UIView) as a member variable I get hundreds of errors, like:

#include <map> : Map no such a file or directory

b
$ b

and in every c++ class/struct:

Expected specifier-qualifier list before ClassName

就像编译器不能识别c ++代码。

Is like compiler is not recognizing c++ code.

我想知道我在这里缺少什么。
它是否必须是这样的事实,我添加到Xcode目标属性:?

I wonder what am I missing here. Does it has to be something with the fact I added this to Xcode Target Properties: ?

Other Link Flags : -lstdc++ -lz

或者我需要在这里添加新标志吗?

Or maybe I need to add new flags here?

提前感谢

推荐答案

您的问题是 .m 文件编译为C而不是C ++。因此,当编译一个 .m 文件时,编译器遇到任何C ++甚至在头文件中时,它都会barf。

Your problem is that .m files are compiled as C instead of C++. Thus when the compiler comes across any C++ even in a header file while compiling a .m file, it will barf.

毫无疑问,你必须在你的头文件中加入一些C ++,因为你的Objective C对象包装了一个C ++对象,但是有一些方法。一种方法是使用指向C ++对象的指针,并使用为C ++(和Objective-C ++)定义的方便的预处理器define __ cplusplus ,而不是C或Objective-C)例如

No doubt you have to put some C++ in your header file because your Objective C object wraps a C++ object, but there are ways around this. One way would be to use a pointer to the C++ object and make use of the handy preprocessor define __cplusplus which is defined for C++ (and Objective-C++) but not for C (or Objective-C) e.g.

// LLAHProcessorWrapper.h

#if defined __cplusplus
class MyCPPClass;    // forward class declaration
#else
typedef struct MyCPPClass MyCPPClass;   // forward struct declaration
#endif

@interface MyOCClass : NSObject
{
@private
    MyCPPClass* cppObject;
} 

// methods and properties

@end

因为你永远不会解除cppObject的成员在 .mm 文件之外,所以你不必为结构提供完整的定义。

Since you never dereference the members of the cppObject outside of the .mm file it doesn't matter that you never provide a full definition for the struct.

您将 delete -init -dealloc 。您将在 LLAHProcessorWrapper.mm 中包含完整的C ++类声明。

You would new and delete the pointer in -init and -dealloc respectively. You would include the full C++ class declaration in LLAHProcessorWrapper.mm.

这篇关于为C ++库创建一个Objective-C包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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