• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Passing a C String as an argument
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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

References: 
 >Passing a C String as an argument (From: Philip Bridson <email@hidden>)

  • Prev by Date: Re: horizontal sizeToFit of NSTextView or NSTextField
  • Next by Date: Re: Binding NSButton enabled state
  • Previous by thread: Re: Passing a C String as an argument
  • Next by thread: Re: Cocoa-dev Digest, Vol 5, Issue 648
  • Index(es):
    • Date
    • Thread