0

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

2
  • Length of an NSString is not equal to the number of bytes of the string. Commented Apr 12, 2011 at 21:47
  • You seem to be badly confused about the difference between C, C++ and Objective-C. C is language, Objective-C is a set of extensions on top of C (i.e. any C code is also Objective-C code), and C++ is a different language based on C. The extension c normally indicates a C file, not C++. And char * is a plain old C type, which means that by definition it's in Objective-C. Commented Apr 12, 2011 at 22:38

2 Answers 2

2

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];
Sign up to request clarification or add additional context in comments.

2 Comments

Little question: do we also need to free fooascii and fooutf8?
short answer: no. but you should definitely read the documentation: developer.apple.com/library/ios/#DOCUMENTATION/Cocoa/Reference/…
0

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.