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 malloc
ed 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,
- If you have got an NSString, don't use
strlen
, use[src length]
instead. - 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:
?
精彩评论