【问题标题】:From NSTextfield to (const unsigned char *) with Swift使用 Swift 从 NSTextfield 到 (const unsigned char *)
【发布时间】:2017-04-03 08:36:00
【问题描述】:

如何在 C 程序中从 Swift 中的 NSTextField 正确接收 (const unsigned char *)?

案例1

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

string1/_core/_baseAddress = nil // 在调试中

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

致命错误:UnsafeRawBufferPointer.load 超出范围

案例2

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

string1/_core/_baseAddress = (_rawValue = 0x... "Test") // 在调试中

致命错误:UnsafeRawBufferPointer.load 超出范围

案例 3

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

string1/_core/_baseAddress = nil // 在调试中

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

testCPgm(string2)

testcfield = "" 在 testCPgm 中

void testCPgm(const unsigned char *testcfield)
{

}

案例4

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

string1/_core/_baseAddress = (_rawValue = 0x... "Test") // 在调试中

testcfield = "" 在 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 中的“测试”

感谢解答

【问题讨论】:

    标签: swift string nstextfield unsafe-pointers


    【解决方案1】:

    这是我没有关闭的发现。

    从字符串 (string1) 到 (const unsigned char *) (string2)

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

    不知道有没有更优雅的方法。

    我没有找到 Data 的等价物(没有关闭)(不是 NSData(使用 .bytes))

    【讨论】:

      猜你喜欢
      • 2011-02-04
      • 2023-04-01
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      相关资源
      最近更新 更多