Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a Objective-C Wrapper for a C++ Library

I am trying to make a wrapper in Objective-C so I don't have to write c++ outside the library classes.

The Library main file is LLAHProcessor.h .cpp

My Wrapper is LLAHProcessorWrapper.h .mm

It compiles fine, but when I add LLAHProcessorWrapper to other class, (Lets say an UIView) as a member variable I get hundreds of errors, like:

#include <map> : Map no such a file or directory

and in every c++ class/struct:

Expected specifier-qualifier list before ClassName

Is like compiler is not recognizing c++ code.

I wonder what am I missing here. Does it has to be something with the fact I added this to Xcode Target Properties: ?

Other Link Flags : -lstdc++ -lz

Or maybe I need to add new flags here?

Thanks in advance

like image 630
nacho4d Avatar asked Nov 17 '10 12:11

nacho4d


People also ask

Is Objective-C compatible with C?

Objective-C is an object-oriented programming language that is a superset of C, as the name of the language might reveal. This means that any valid C program will compile with an Objective-C compiler. It derives all its non-object oriented syntax from C and its object oriented syntax from SmallTalk.

Can I use C code in Swift?

C function pointers are imported into Swift as closures with the C function pointer calling convention, denoted by the @convention(c) attribute. For example, a function pointer that has the type int (*)(void) in C is imported into Swift as @convention(c) () -> Int32 .

Is C faster than Objective-C?

Objective-C is slightly slower than straight C function calls because of the lookups involved in its dynamic nature.


1 Answers

Your problem is that .m files are compiled as C instead of C++. Thus when the compiler comes across any C++ even in a header file while compiling a .m file, it will barf.

No doubt you have to put some C++ in your header file because your Objective C object wraps a C++ object, but there are ways around this. One way would be to use a pointer to the C++ object and make use of the handy preprocessor define __cplusplus which is defined for C++ (and Objective-C++) but not for C (or Objective-C) e.g.

// LLAHProcessorWrapper.h

#if defined __cplusplus
class MyCPPClass;    // forward class declaration
#else
typedef struct MyCPPClass MyCPPClass;   // forward struct declaration
#endif

@interface MyOCClass : NSObject
{
@private
    MyCPPClass* cppObject;
} 

// methods and properties

@end

Since you never dereference the members of the cppObject outside of the .mm file it doesn't matter that you never provide a full definition for the struct.

You would new and delete the pointer in -init and -dealloc respectively. You would include the full C++ class declaration in LLAHProcessorWrapper.mm.

like image 96
JeremyP Avatar answered Sep 22 '22 03:09

JeremyP