开发者

NSString to C string

开发者 https://www.devze.com 2023-01-07 06:57 出处:网络
I\'m new with Objective C. I would like to know why this code does not work fine. The idea is to make a function that copies the content of a NSString into a Cstring.

I'm new with Objective C.

I would like to know why this code does not work fine. The idea is to make a function that copies the content of a NSString into a Cstring.

I send a message to setAttr, i.e: [ self setAttr:@"something"]

- (BOOL) setAttr:(NSString *) src{
 const char *dst;

 [ self NSString2CString: src  dst: dst ];

 printf("%s",dst); // <-- gives me junk
 return YES;
}


- (BOOL) NSString2CString: (NSString *) src dst: (const char *) dst {
 const char * __src= [src UTF8String];
 if ( (dst=(const char *) malloc( strlen(__src)+ 1) ) == NULL) retur开发者_开发百科n NO;
 strcpy(dst, __src);
 return YES;
} 

thanks


In the method -NSString2CString:dst:, dst is a local variable. Your malloc to dst won't be reflected back to the caller.

To allow the caller to receive the new malloced pointer, you need to pass by reference:

-(BOOL)NSString2CString:(NSString*)src dst:(char**)p_dst {
//                                     ^^^^^^^^^^^^^^^^^
   ...
   if ( (*p_dst = malloc( ... )) == NULL ) return NO;
   strcpy(*p_dst, __src);
}
...
char* dst;
[self NSString2CString:src dst:&dst];

BTW,

  1. If you have got an NSString, don't use strlen, use [src length] instead.
  2. You know there's already a method called -getCString:maxLength:encoding:?


You need to pass in the address of the cstring (using the address-of operator &) not the pointer:

[ self NSString2CString: src dst: &dst ];

Your method prototype should now look like this:

- (BOOL) NSString2CString: (NSString *) src dst: (const char **) dst

But why do this when NSString already has a method called -getCString:maxLength:encoding:?

0

精彩评论

暂无评论...
验证码 换一张
取 消