From NSTextfield to (const unsigned char *) with Swift



我怎样才能从 Swift 中的 NSTextField 正确接收 C 程序中的 (const 无符号字符 *(?

案例 1

let string1 = atextfield!.stringValue // -> "Test"
print(string1) // -> "Test"

字符串1/_core/_baseAddress = 无//在调试中

let string2 = string1.utf8CString.withUnsafeBytes
{
    ptr -> UnsafePointer<UInt8> in
    return ptr.load(as: UnsafePointer<UInt8>.self)
}

致命错误:UnsafeRawBufferPointer.load Out of bounds

案例 2

let string1 = "Test"
print(string1) // -> "Test"

字符串1/_core/_baseAddress = (_rawValue = 0x..."测试"(//在调试中

致命错误:UnsafeRawBufferPointer.load Out of bounds

案例 3

let string1 = atextfield!.stringValue // Value = "Test"
print(string1) // -> "Test"

字符串1/_core/_baseAddress = 无//在调试中

let string2 :UnsafePointer<UInt8> = string1.utf8CString.withUnsafeBufferPointer {
($0.baseAddress!.withMemoryRebound(to: UnsafePointer<UInt8>.self, capacity: string1.lengthOfBytes(using: .utf8)) {$0})}.pointee
testCPgm(string2)

testcfield = " in testCPgm

void testCPgm(const unsigned char *testcfield)
{
}

案例4

let string1 = "Test"
print(string1) // -> "Test"

字符串1/_core/_baseAddress = (_rawValue = 0x..."测试"(//在调试中

testcfield = " in testCPgm

案例 5 --> 它有效!

let string1 = "Test"
or
let string1 = atextfield!.stringValue
print(string1) // -> "Test"
testCPgm(string1) // Yes directly from String to (const unsigned char *)

testcfield = testCPgm 中的"Test">

感谢您的回答

这是我在没有关闭的情况下发现的。

从字符串 (字符串 1( 到 (常量无符号字符 *( (字符串 2(

let string2 = UnsafeRawPointer(string1.cString(using: .utf8)).bindMemory(to: CUnsignedChar.self, capacity: string1.lengthOfBytes(using: .utf8))

我不知道是否有更优雅的方法。

我没有找到数据的等效项(没有闭包((不是 NSData(使用 .bytes((

最新更新