Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an Objective-C class method from C++

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

In my .h:

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

In my .m:

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

In my .cpp:

??

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

Thanks

like image 665
Asheh Avatar asked Dec 27 '22 07:12

Asheh


1 Answers

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. Use Objective-C++. Rename your .cpp to .mm, then you can use Objective-C syntax in your C++ code: [FlurryAnalytics myMethod: @"foo"];

  2. 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.

  3. 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.

like image 179
wolfgang Avatar answered Dec 29 '22 21:12

wolfgang