Reputation: 9431
Is there any way to call c++ functions from objective-c code without .mm extension? For example maybe it is possible to create a C wrapper or anything else that can help in this situation? I know that it is possible assign type "objective-c++ source" for .m files but it is not what I want.
Upvotes: 3
Views: 138
Reputation: 6831
Using Objective-C++ is the eaiser way to go, but if for some reason you can't use it* you can go through a C wrapper, but it has to be purely C. So it will look something like this:
//MyClass.h
class MyClass {
public:
MyClass() : myInt(10) {}
~MyClass() {}
int GetMyInt() const {return myInt;}
private:
int myInt;
}
//MyClassWrap.h
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {void * myClass} MyClassWrap;
MyClassWrap CreateMyClass();
void DestroyMyClass(MyClassWrap myClass);
int GetMyInt(MyClassWrap myClass);
#ifdef __cplusplus
}
#endif
//MyClassWrap.cpp
#include "MyClassWrap.h"
#include "MyClass.h"
static void * implCreate()
{
return static_cast<void *>(new MyClass());
}
static void implDestroy(void * myClass)
{
delete static_cast<MyClass *>(myClass);
}
static int implGetMyInt(void * myClass)
{
return static_cast<MyClass *>(myClass)->GetMyInt();
}
extern "C" {
MyClassWrap CreateMyClass() {
MyClassWrap wrap;
wrap.myClass=implCreate();
return wrap;
}
void DestroyMyClass(MyClassWrap myClass) {
implDestroy(myClass.myClass);
}
int GetMyInt(MyClassWrap myClass) {
return implGetMyInt(myClass.myClass);
}
} //extern "C"
Having the separate impl*
functions might not be necessary, it's been a while since I've done something like this. With this appoach, you can include MyClassWrap.h
in an Objective-C file and indirectly get access to C++ functions with no files compiled as Objective-C++.
*Maybe too many variables named class in code you can't change
Upvotes: 1
Reputation: 299275
Yes, I do this often. You will need a small amount of .mm
glue code, but your intuition of using wrappers is correct. You may be interested in Wrapping C++ - Take 2.
There are good reasons to avoid excessive use of .mm files. They compile slower, run slower (particularly under ARC where they incur significant overhead), confuse gdb in my experience, and the mixing of ObjC and C++ classes is quite confusing and error-prone. Segmenting your ObjC and C++ with a thin layer between them is a good approach.
Upvotes: 5