开发者

Casting void* to NSString* without stringWithCString

开发者 https://www.devze.com 2023-01-28 01:32 出处:网络
I have a program that is interacting with the Keychain. 开发者_开发知识库You pass in a pointer to a void pointer and the keychain directs it, I guess, to the password, you also pass in a UInt32 pointe

I have a program that is interacting with the Keychain. 开发者_开发知识库You pass in a pointer to a void pointer and the keychain directs it, I guess, to the password, you also pass in a UInt32 pointer and it will point to the length of the password.

I then need to use this as a NSString, I tried to directly cast it as such but it was aggregating more bits then needed and that won't work for a password. I tried to use:

NSString* password=[NSString stringWithCharacters:passwordData length:passwordLength];

This changed password into chinese like characters. Not sure why. When I print the description in debug mode it gives me:

Printing description of password:
\u3039\u4839\u6d6f\u2165\u1566�

I was able to get it to work perfectly with:

NSString* password=[NSString stringWithCString:passwordData length:passwordLength];

but this was depreciated and I would like to avoid using that. I am very new to both C and Objective-C and void pointers throw me for a loop. In debug mode I looked at the memory that the pointer was pointing to and it is definitely at that memory location. I tried using const char* but it didn't like that either saying that the variables may not have been initialized.

Here is the method I am using to get to the keychain

- (OSStatus) GetPasswordKeychain:(void*)passwordData length:(UInt32*)passwordLength label:(NSString*)serverName
{
 status=SecKeychainFindGenericPassword(NULL, (UInt32)[serverName length], [serverName UTF8String], usernameLength, username,passwordLength , passwordData, NULL);
return status;
}

Is there a way to get a NSString to point there with the right length and have it be the right stuff. Thanks for the help. This place is great!


After scouring the Apple website I discovered the method:

- (id)initWithBytes:(const void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding

and that works great.


stringWithCString has been depreciated in 10.5 to but i never found a nice replacement until now:

message = [NSString stringWithCString:(buffer + 4) length:(arg2 -5)];

becomes:

message = [[[NSString alloc] initWithBytes:(buffer + 4) length:(arg2 -5) encoding:NSASCIIStringEncoding] autorelease];

0

精彩评论

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