I am new with kotlin multiplatform I want to convert this function from objective C to kotlin
NSString *RCTMD5Hash(NSString *string)
{
const char *str = string.UTF8String;
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, (CC_LONG)strlen(str), result);
return [NSString stringWithFormat:@"xxxxxxxxxxxxxxxx",
result[0],
result[1],
result[2],
result[3],
result[4],
result[5],
result[6],
result[7],
result[8],
result[9],
result[10],
result[11],
result[12],
result[13],
result[14],
result[15]];
}
My kotlin code:
fun md5Hash(key: NSString): String {
val str = key.UTF8String
val result = alloc<UByteVar>()
CC_MD5(str, strlen(str.toString()).toCC_LONG(), result)
return NSString.stringWithFormat("xxxxxxxxxxxxxxxx", result[0],
result[1],
result[2],
result[3],
result[4],
result[5],
result[6],
result[7],
result[8],
result[9],
result[10],
result[11],
result[12],
result[13],
result[14],
result[15])
}
I got some error can not resolve
CodePudding user response:
To allocate C memory in Kotlin, memScoped
should be used.
In your case you need to allocate an array, that's why allocArray
should be used instead of a alloc
:
fun md5Hash(key: NSString): String {
memScoped {
val str = key.UTF8String
val result = allocArray<UByteVar>(CC_MD5_DIGEST_LENGTH)
CC_MD5(str, strlen(key.toString()).toUInt(), result)
return NSString.stringWithFormat(
"xxxxxxxxxxxxxxxx",
result[0],
result[1],
result[2],
result[3],
result[4],
result[5],
result[6],
result[7],
result[8],
result[9],
result[10],
result[11],
result[12],
result[13],
result[14],
result[15]
)
}
}