简体   繁体   English

NSDictionary-C ++中的Objective-C代码

[英]NSDictionary - Objective-C code in C++

Is it possible to use NSDictionary inside C++ class ? 是否可以在C ++类中使用NSDictionary I know, I can use Objective-C classes inside C++ ( http://philjordan.eu/article/mixing-objective-c-c++-and-objective-c++ ), but for NSDictionary , I need header... but if I do #import , it failed to compile. 我知道,我可以在C ++中使用Objective-C类( http://philjordan.eu/article/mixing-objective-c-c++-and-objective-c++ ),但是对于NSDictionary ,我需要标头...但是如果我执行#import ,无法编译。

PS: I know, I shouldnt mix Objective-C(++) and C++ , but I am writing multiplatform OpenGL app and for EAGL initialization one of input parametrs is NSDictionary . PS:我知道,我不应该混合使用Objective-C(++)C ++ ,但是我正在编写多平台OpenGL应用程序,对于EAGL初始化,输入参数之一是NSDictionary I could init OpenGL in Objective-C , but it would break my OOP design. 我可以在Objective-C中初始化OpenGL,但这会破坏我的OOP设计。

Sure compile the C++ class as Objective-C++ (.mm extension) and you will have no problems. 确保将C ++类编译为Objective-C ++(扩展名为.mm),并且不会有任何问题。 The only problem I've had doing this is the fact that you can't define the Objective-C++ type inside the C++ header. 我这样做的唯一问题是您无法在C ++标头中定义Objective-C ++类型。 So instead I use a void* and cast it to void* using a 因此,我改用void *并使用a将其转换为void *

pVoidDict = (__bridge_retained void*)[NSDictionary dictionary];

You will need to perform a bridged cast to use it: 您将需要执行桥接演员表才能使用它:

unsigned int dictCount = [(__bridge NSDictionary*)pVoidDict count];

The only problem is you must remember to release it at the end. 唯一的问题是您必须记住在最后将其释放。 You can do this by casting it back to an NSDictionary as follows: 您可以按照以下步骤将其投射回NSDictionary:

NSDictionary* dict = (__bridge_transfer NSDictionary*)pVoidDict;

This will return it to ARC control and when the destructor exits it will be added to the autorelease pool as per standard ARC rules. 这会将其返回到ARC控制,并且在析构函数退出时,将根据标准ARC规则将其添加到自动释放池中。

Its not particularly nice to look at but I use this quite a bit in a cross-platform library so that I can wrap Objective-C objects with C++ classes. 看起来不是特别好,但是我在跨平台库中使用了很多,以便可以用C ++类包装Objective-C对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM