2016-05-09

How to call Objective-C method from C++

I know the way of calling Objective-C method from C++ file without connecting file for them. Check this below and you will notice how easy it is. Also, this is available for Cocos2d-x project.

Files

SubView.h (A header file for getting call)
  1. // The class from C++ call
  2. class SubView
  3. {
  4. public:
  5. // Getting call from C++
  6. static void callObjC();
  7. };

SubView.mm (A source file for getting call)
  1. #import "SubView.h"
  2.  
  3. // Not in header file.
  4. @interface ClassObjC : NSObject
  5.  
  6. + (void)testingMethod;
  7.  
  8. @end
  9.  
  10. // Objective-C class in source file as normal way
  11. @implementation ClassObjC
  12.  
  13. //--------------------------------------------------
  14. // [Objective-C] for testing
  15. //--------------------------------------------------
  16. + (void)testingMethod
  17. {
  18. NSLog(@"I was called from C++");
  19. }
  20.  
  21. @end
  22.  
  23. //==================================================
  24. // [C++] Call the method of Objective-C class
  25. //==================================================
  26. void SubView::callObjC()
  27. {
  28. [ClassObjC testingMethod];
  29. }

MainView.cpp (For calling Objective-C)
  1. #include "SubView.h"
  2.  
  3. void MainView::mainFunc()
  4. {
  5. SubView::callObjC();
  6. }

Short Description

This is like portal for C++ in Objective-C file.
The number of functions is here.
  1. MainView::mainFunc()
  2. SubView::callObjC()
  3. [ClassObjC testingMethod]
Such as, if your project has Objective-C file, replace the class interface to the source file from the header file, and just add the C++ coding then done. Also remind this file extension need to be ".mm".