2017-04-03 39 views
0

我怎样才能正确地收到一个(const无符号字符*)在C程序从一个NSTextField在Swift中?从NSTextfield到(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出界

案例2的

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

字符串1/_Core/_baseAddress =(_rawValue = 0X ...... “测试”)//在调试

致命错误:UnsafeRawBufferPointer.load出界

案例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 = “” 在testCPgm

void testCPgm(const unsigned char *testcfield) 
{ 

} 

案例4

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

字符串1/_Core/_baseAddress =(_rawValue = 0X ...... “测试”)//在调试

testcfield =“”in testCPgm

Case 5 - >It Works!

let string1 = "Test" 

or 

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

testCPgm(string1) // Yes directly from String to (const unsigned char *) 

testcfield = “测试” 在testCPgm

感谢答案

回答

0

这是我发现没有关闭。

从字符串(字符串1)至(const的无符号字符*)(字符串2)

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

我不知道是否有一个更优雅的方式来做到这一点。

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