Re: Passing a C String as an argument
Re: Passing a C String as an argument
- Subject: Re: Passing a C String as an argument
- From: Jens Alfke <email@hidden>
- Date: Sun, 20 Apr 2008 11:39:16 -0700
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
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden