Re: NSString array to -> char**
Re: NSString array to -> char**
- Subject: Re: NSString array to -> char**
- From: Thomas Lachand-Robert <email@hidden>
- Date: Sun, 16 Mar 2003 15:35:15 +0100
Le dimanche, 16 mars 2003, ` 05:23 Europe/Paris, Seth Delackner a icrit
:
Has anyone come up with a better method of converting a set of
NSStrings to a char** that can be passed to library functions
expecting an array of cstrings?
My solution below is nasty, because it trusts the user to free the
memory (when they probably have no idea what the size of the memory
is):
Here is a different way of doing that: use NSData (or NSMutableData if
you need a mutable array of C strings). NSData is basically a block of
memory, and here it would contain not only the actual char** array in
front, but also all the char* after that, including the null char
terminator. Note that NSMutableData will do the hard work for you
(managing the size of the block, reallocate it, etc.), and you can send
it autoreleased as usual, so that you are sure not to leak memory.
Finally you can implement everything as a category on NSMutableData (or
NSData), so you don't need any new class, etc. Using [myData bytes] (or
mutableBytes) will return the desired char**.
Here is a rough implementation (typed in Mail). Note that I assume here
an NSArray of NSString, so you can use:
myData = [NSMutableData dataAsArrayOfCStrings:[NSArray
arrayWithObjects:string1, string2, string3, nil]
usingEncoding: NSASCIIStringEncoding];
myFunctionWithParameterCharStarStar([myData bytes]);
for instance if you have a list of NSStrings.
@implementation NSMutableData (arrayOfCStrings)
+(NSMutableData*) dataAsArrayOfCStrings:(NSArray*)strings
usingEncoding:(NSStringEncoding)encoding
{
unsigned n = [strings count];
NSMutableData *data = [NSMutableData dataWithLength:
(n+1)*sizeof(char*)],
NSEnumerator* en = [strings objectEnumerator];
NSString* s; unsigned k = 0;
while ((s = [enumerator nextObject])) {
int* stringsLength;
// I'm not sure if dataUsingEncoding add a null terminator, please
check this
NSData* tempData = [s dataUsingEncoding:encoding
allowLossyConversion:YES];
[data append
Data:tempData];
// we need to refetch stringsLength, since this can change with
appendData
stringsLength = (int*)[data mutableBytes];
stringsLength[k++] = [tempData length];
}
// now we have the strings lengths in front of the array, we want
pointers instead
char *p = [data mutableBytes], *q=p;
while (k--) q++ = p + *(int*)q;
q = NULL; // NULL terminated array
return data; // that's all folks
}
Thomas Lachand-Robert
********************** email@hidden
<< Et le chemin est long du projet ` la chose. >> Molihre, Tartuffe.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.