user440096
user440096

Reputation:

Calling C++ methods from your objective-c code

I have some C classes imported into my app. So along with my .h and .m objective-c classes I have some .h and .c C++ classes. Is it ok to do this? Or do i need to compile them into a .a so they can be used?

Assuming its all ok to do what I have done, I want to call this C++ method

mms_t *mms_connect (mms_io_t *io, void *data, const char *url, const char *host, const char *uri,const  char *query,int pport, int bandwidth) 

So this method returns a struct called mms_t ?

It requires I pass in some char*. In Objective-C what can i pass in here? Are there char* in this language? I'm guessing I cant pass in a NSString in its place?

I see from a little snippet of C code

    strTemp = @"mms://123.30.49.85/htv2";

char *g_tcUrl = new char[[strTemp length] + 1];

'new' is used?

Whats the objective c equivalent of the above code?

Many Thanks, -Code

Upvotes: 0

Views: 1025

Answers (2)

Jim Blackler
Jim Blackler

Reputation: 23169

You can freely call across Objective C and C++, in fact mix them up in virtually any combination. All you need to do is convert types where appropriate. You will need your code files to be named .mm (technically Objective C++ files) not .m files to include C++ header files.

To convert Objective C string to C style strings do:

const char *cString = [strTemp cStringUsingEncoding:NSUTF8StringEncoding];

Upvotes: 0

Can Berk Güder
Can Berk Güder

Reputation: 113310

First of all, you would have to change the type of your Objective-C file to Objective-C++. You can do this by changing the file extension to .mm or by using the file info panel (ctrl-click, get info).

For char*, you can convert an NSString to a C string using either UTF8String or cStringUsingEncoding: like this:

NSString *foo = @"Foo";
char *fooascii = [foo cStringUsingEncoding:NSASCIIStringEncoding];
char *fooutf8 = [foo UTF8String];

Upvotes: 2

Related Questions