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
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 mails | Author | Date |
|---|---|---|
| Philip Bridson | Apr 20, 19:17 | |
| Clark Cox | Apr 20, 19:33 | |
| Jens Alfke | Apr 20, 20:39 | |
| William Squires | Apr 21, 04:06 |






Cocoa mail archive

