我试过这个
return areKeysConsistent(
certificate as! UnsafeMutablePointer<UInt8>,
certificate.lengthOfBytes(using: <#T##String.Encoding#>.utf8),
privateKey as! UnsafeMutablePointer<UInt8>,
privateKey.lengthOfBytes(using: <#T##String.Encoding#>.utf8),
password as! UnsafeMutablePointer<UInt8>
)
但是IDE说
- “字符串始终失败。
转换它的正确方法是什么?,谢谢
答案 0 :(得分:1)
这是您必须使用C语言时遇到的一些复杂问题。
这里主要关注的是传递给该函数的指针的生命周期。我下面的代码使用指向Swift字符串缓冲区的指针。如果areKeysConsistent
捕获这些指针供以后使用,这将是一个问题。 ARC可能会释放Swift字符串,使这些存储的指针成为悬空指针。
func areKeysConsistent(
_ cert: UnsafeMutablePointer<UInt8>, _ certLength: Int,
_ key: UnsafeMutablePointer<UInt8>, _ keyLength: Int,
_ pass: UnsafeMutablePointer<UInt8>, _ passLength: Int
) {
print(cert, key, pass)
}
let certificate = "cert"
let privateKey = "key"
let password = "password"
var certificateCString = certificate.utf8CString
var privateKeyCString = privateKey.utf8CString
var passwordCString = password.utf8CString
certificateCString.withUnsafeMutableBytes { certUMRBP in
privateKeyCString.withUnsafeMutableBytes { pkUMRBP in
passwordCString.withUnsafeMutableBytes { passUMRBP in
areKeysConsistent(
certUMRBP.baseAddress!.bindMemory(to: UInt8.self, capacity: certUMRBP.count),
certUMRBP.count,
pkUMRBP.baseAddress!.bindMemory(to: UInt8.self, capacity: pkUMRBP.count),
pkUMRBP.count,
passUMRBP.baseAddress!.bindMemory(to: UInt8.self, capacity: passUMRBP.count),
passUMRBP.count
)
}
}
}
答案 1 :(得分:0)
感谢@Alexander解决了我的问题,这是我的代码:
var string = 'word word words things amazing icons yup'
console.log(string)
string = string.replace(/(\S)(\S*)/g, function (_, first, rest) {
return first.toUpperCase() + rest
})
console.log(string)
答案 2 :(得分:0)
尝试一下(快速4):
func stringToUnsafeMutablePointer(message: String) -> UnsafeMutablePointer<Int8> {
var messageCString = message.utf8CString
return messageCString.withUnsafeMutableBytes { mesUMRBP in
return mesUMRBP.baseAddress!.bindMemory(to: Int8.self, capacity: mesUMRBP.count)
}
}