1

I have a c++ project that needs to make use of an objective-C SDK. My idea is to create a c++ class in a .mm file which contains calls to the SDK in objective-C syntax. Then I would declare an instance of that class in my existing c++ project (which has .cpp files).

Will that work? From what I gather, a ".mm" file is an Objective-C++ file, which can make calls to Objective-C functions? But can a cpp file instanciate a class defined in a .mm file?

user1070447
  • 147
  • 10

1 Answers1

1

Define the class in a header and include it in both the Objective-C++ file that defines members of the class and the C++ file that uses the class.

If you need to store Objective-C types, wrap them in an opaque structure.

Illustration:

"C.h":

class C
{
    public:
        C();
        void foo();
    private:
        struct Data;
        Data* m_data;
};

Implementation in Objective-C++:

#include "C.h"

struct C::Data
{
    SomeTypeInYourSDK* thing;
};

C::C()
{
    m_data = new Data;
    m_data->thing = [SomeTypeInYourSDK createSomehow];
}

void C::foo()
{
    [m_data->thing doSomething];
}

Use in C++:

#include "C.h"

void bar()
{
    C c;
    c.foo();
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • Thanks! Follow up question: if it is the case that it can be implemented in this way, why did this user recommend to create an interface, rather than simply doing it the way you said? http://stackoverflow.com/questions/1061005/calling-objective-c-method-from-c-method What is the point of his/her method? – user1070447 Jul 09 '15 at 01:34
  • The second solution in that answer is the same as this. The first solution provides a C interface rather than a C++ interface, which is good if you're using C or a language that can interface with C libraries (and many can, these days). – molbdnilo Jul 09 '15 at 06:42