从C ++调用Objective-C类方法 [英] Calling an Objective-C class method from C++

查看:119
本文介绍了从C ++调用Objective-C类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从C ++文件调用Objective-C类方法时遇到麻烦.示例:

I am having some trouble calling an objective-c class method from a C++ file. Example:

在我的.h中:

@interface MyClass : NSObject {
}
+ (void)myMethod:(NSString *)str;

在我的.m中:

+ (void) myMethod:(NSString *)str { ... }

在我的.cpp中:

??

由于没有类实例,如何调用myMethod?它本质上是静态的吗?

How can you call myMethod since there is no class instance? Its essentially a static?

谢谢

推荐答案

C ++中的对象与Objective-C中的对象不兼容.您不能简单地从C ++调用Objective-C方法.

Objects in C++ are incompatible with objects in Objective-C. You cannot simply call an Objective-C method from C++.

但是,有一些解决方案:

There are some solutions, however:

  1. 使用Objective-C ++.将.cpp重命名为.mm,然后可以在C ++代码中使用Objective-C语法:[FlurryAnalytics myMethod: @"foo"];

  1. Use Objective-C++. Rename your .cpp to .mm, then you can use Objective-C syntax in your C++ code: [FlurryAnalytics myMethod: @"foo"];

使用对Objective-C运行时系统的直接调用.我不会告诉你怎么做,因为我真的认为你不应该,事实上你也不想.

Use direct calls to the Objective-C runtime system. I won't tell you how to, because I really think you shouldn't, and in fact that you don't want to.

编写纯C接口.也就是说,在某些.m文件中,定义void myFunction(const char *str) { ... }并从C ++调用它.您可以在此处找到示例.

Write a plain-C interface. That is, in some .m file, define void myFunction(const char *str) { ... } and call that from C++. You can find an example of this here.

这篇关于从C ++调用Objective-C类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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