4

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

hich9n
  • 1,578
  • 2
  • 15
  • 32
Asheh
  • 1,547
  • 16
  • 25
  • Possible duplicate of [Calling Objective-C method from C++ method?](https://stackoverflow.com/questions/1061005/calling-objective-c-method-from-c-method) – Victor Sergienko Oct 14 '17 at 17:46

2 Answers2

8

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.

wolfgang
  • 4,883
  • 22
  • 27
  • I think generating some global data on the C++ side and accessing it with objective-c is going to be the most viable option. – Asheh Jan 13 '12 at 14:19
2

You're going to need a .mm to call an Objective-C method, rather than a .cpp. Beyond that your comment that 'it's essentially static' is accurate in the sense that you would call it with similar logic to the way you would call static class functions in C++:

[MyClass myMethod:@"Some String"];

Though the method isn't static in the C++ sense for a bunch of reasons that don't affect this answer — it isn't resolved at compile time and it does operate within a class (the MyClass metaclass).

Tommy
  • 99,986
  • 12
  • 185
  • 204
  • If I dont have the option of converting all .cpp files to .mm, what options do i have? Im trying to maintain cross platform capabilitys so I cant go changing file types. – Asheh Jan 13 '12 at 14:16
  • .cpp files can call any old C++ and .mm files contain C++ and Objective-C so a thin platform-specific layer is one option; alternatively in Xcode open out the right hand panel using the button above the word 'View' on the toolbar, go to 'Identity and Type' and set the file type to Objective-C++. That should cause relevant flags to be sent to the compiler so that the default behaviour of type-by-filename isn't followed. – Tommy Jan 13 '12 at 14:40
  • @Asheh: You can override the file type in Xcode. Click on the .cpp file in the project navigator and the File inspector will show a drop down list called "File Type". Change this from Default to Objective-C++ source and then your cpp file can contain Objective C syntax as if it were a .mm – JeremyP Jan 13 '12 at 15:39