Skip navigation.
 
mlRe: Passing a C String as an argument
FROM : Jens Alfke
DATE : Sun Apr 20 20:39:16 2008

On 20 Apr '08, at 10:17 AM, Philip Bridson wrote:

> Is there anyway to pass a C string from a Obj-C class to a C 
> function as an argument? I know that I can use pointers to the 
> string but it gets a bit messy as I am using pointers in the C 
> function to manipulate the string.


It sounds like what you want is to pass a copy of the C string to the 
function, so it can internally make changes to it without messing up 
the original string?

For this, use the standard C function strdup (run 'man strdup' in a 
shell to see the docs). Use it like this:

   - (void) myMethod: (NSString*)str {
       char *cstr = strdup( [str UTF8String] );
       myCFunction(cstr);
       free(cstr);
   }

Note that the return value of strdup is a malloc'ed block that has to 
be freed when you're done with it.
Also note that the malloc block is the exact size of the string and no 
longer, so the one thing you can't do is make the string longer, or 
you'll write past the end of the block and corrupt the heap or crash. 
(If you need to do that, you'll have to allocate a long-enough block 
yourself with malloc, and then call strcpy to copy the string into it.)

—Jens

Related mailsAuthorDate
mlPassing a C String as an argument Philip Bridson Apr 20, 19:17
mlRe: Passing a C String as an argument Clark Cox Apr 20, 19:33
mlRe: Passing a C String as an argument Jens Alfke Apr 20, 20:39
mlRe: Passing a C String as an argument William Squires Apr 21, 04:06