Hex string to UnsafePointer<Int8> swift

202 views Asked by At

I am looking a better way to convert a hex string to an array of UnsafePointer. here is my current code:

let pointer: UnsafePointer<Int8>? = NSString(string: "d0c6a560de2e60b6ac55386defefdf93b0c907290c2ad1b4dbd3338186bfdc68").utf8String
// or 
let pointer: UnsafePointer<Int8>? = NSString(string: key).utf8String
let length = NSString(string: key).length
var res =  blsSecretKeySetHexStr(&sec, pointer, length)

I'm porting a C++ class to Swift and this class methods blsSecretKeySetHexStr and blsPublicKeyGetHexStr require UnsafePointer and UnsafeMutablePointer as input.

1

There are 1 answers

0
AnderCover On

You can find useful informations about UnsafePointer usage here.

First if you have want to pass a pointer to a string to a function accepting an UnsafePointer<Int8> you can simply do :

func foo(pointer: UnsafePointer<Int8>) {
    print(pointer) // 0x0000600003478c60
    print(strlen(pointer)) // 64
}

let immutableString = "d0c6a560de2e60b6ac55386defefdf93b0c907290c2ad1b4dbd3338186bfdc68"

foo(pointer: immutableString)
// 0x0000600003478c60
// 64

or

let cStringPointer = immutableString.utf8CString
    .withUnsafeBufferPointer { $0 }
    .baseAddress!
foo(pointer: cStringPointer)
// 0x0000600003478c60
// 64

or

var cstring = immutableString.cString(using: .utf8)!
foo(pointer: &cstring)
// 0x00006000023e0950
// 64

if you need an UnsafeMutablePointer :

func bar(pointer: UnsafeMutablePointer<CChar>) {
    print(pointer)
    print(strlen(pointer))
}

let string = "d0c6a560de2e60b6ac55386defefdf93b0c907290c2ad1b4dbd3338186bfdc68"
var cstring = string.cString(using: .utf8)!
bar(pointer: &cstring)
// 0x00006000023e0950
// 64

or

var mutableCString = immutableString.utf8CString
let mutableCStringPointer = mutableCString
    .withUnsafeMutableBufferPointer { $0 }
    .baseAddress!
bar(pointer: cStringMutablePointer)
// 0x0000600003478c60
// 64