2017-04-03 55 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))