Droidme
Droidme

Reputation: 1252

Calling C++ function from objective C class

I want to call a c++ function from my objective C class i am not sure how to call it.Please somebody help me by giving some sample codes or useful links Thanks in advance

Upvotes: 2

Views: 4345

Answers (3)

mahboudz
mahboudz

Reputation: 39376

Expanding on what pmjordan said, if you have a .m file calling in to a .mm or .cpp, make sure that the main header of the .mm or .cpp, where the functions you are calling are declared, have conditionally compiled extern "C" like this .h file:

#ifdef __cplusplus
extern "C" {
#endif

void functionA(void);
void functionB(const char *);

#ifdef __cplusplus
}
#endif

When this header is included as part of the .mm or .cpp, the extern "C" will do the right thing, and when the .h is compiled as part of the calling .c or .m file that calls those functions, the extern "c" is excluded and will not cause the compiler to complain.

Using this solution will prevent you from needlessly changing .m files into .mm files just so you can simply call C routines in c++ files.

Upvotes: 0

pmdj
pmdj

Reputation: 23428

An alternative to switching your class implementation file to Objective-C++ is to declare the C++ function as extern "C", assuming its arguments are all C types. Place that declaration inside a C-compatible C++ header file and include it from both the C++ file that implements the function and from the Objective-C file that calls it. This will of course only work if the data types of parameters and the return type are pure C types, but is in some cases "cleaner" than the Objective-C++ approach.

Upvotes: 2

Joe
Joe

Reputation: 57179

Change the .m extension to .mm on the Objective-C file to make it Objective-C++.

Upvotes: 6

Related Questions