简体   繁体   English

混合Objective-C和C ++代码

[英]Mixing Objective-C and C++ code

I have an Objective-C/C++ application which uses functionality that is provided by a C++ library. 我有一个Objective-C / C ++应用程序,它使用C ++库提供的功能。

One of the C++ classes includes an enum like this: 其中一个C ++类包含这样的枚举:

class TheClass
{
public:
[...]

enum TheEnum
{
    YES,
    NO,
};

[...]
};

Including (using #import -if that matters-) a header file with the above class declaration in an Objective-C/C++ source file (*.mm) will make the compile fail since the preprocessor will replace "YES" by the term "(BOOL) 1" (and likewise "NO" by "(BOOL) 0"). 包括(使用#import -if that matters-)带有Objective-C / C ++源文件(* .mm)中的上述类声明的头文件将使编译失败,因为预处理器将用术语“替换”为“YES” (BOOL)1“(”(BOOL)0“同样为”NO“)。

Is there a way to fix that without renaming the values of the enum? 有没有办法解决这个问题而不重命名枚举的值?

YES and NO are predefined constants in Objective-C, declared in the objc.h header. YES和NO是 Objective-C 中预定义的常量 ,在objc.h头文件中声明。

You should be able to prevent the preprocessor to expand the "YES" and "NO" macro's. 您应该能够阻止预处理器扩展“是”和“否”宏。 This can be done by locally #undef fing them. 这可以通过本地#undef fing来完成。

But technically, if you're using a language keyword as an identifier, you can expect trouble. 但从技术上讲,如果您使用语言关键字作为标识符,则可能会遇到麻烦。 You won't write a class containing a member called MAX_PATH , would you? 你不会写一个包含名为MAX_PATH的成员的类,对吗?

The #import does matter -- C++ headers in an Objective-C++ source file should be included with #include . #import重要 - Objective-C ++源文件中的C ++头文件应包含在 #include I think, though am not 100% sure, that the choice of include directive ( #include vs #import ) determines which preprocessor is used. 我认为,尽管不是100%肯定,但是include指令( #include vs #import )的选择决定了使用哪个预处理器。

\n

You could also reverse the declaration of the constants in the enum, since by default, members of an enum are associated with integers starting from 0. 您还可以反转枚举中常量的声明,因为默认情况下,枚举的成员与从0开始的整数相关联。

Per comments, I'm wrong. 根据评论,我错了。 Looks like you'll have to rewrite the enum. 看起来你必须重写枚举。 Sorry :( 对不起:(

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

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