在我的swift應用程序項目中,我必須與C API進行交互。其中一個C函數將char指針作爲輸入,因此我必須將我的swift字符串轉換爲char指針。但我不知道如何正確地做到這一點。將Swift字符串轉換爲CChar指針
這裏是我的示例代碼:
var user_id_ptr : UnsafeMutablePointer<CChar> = UnsafeMutablePointer.alloc(100)
var cusID = "123"
user_id_ptr.memory = cusID.cStringUsingEncoding(NSUTF8StringEncoding)!
我總是得到這個錯誤: Cannot assign a value of type '[CChar]' to a value of type 'CChar'
我也查了答案:UnsafeMutablePointer<Int8> from String in Swift
上面的回答是我的略有不同。 上面的示例僅適用於一個字符,但我有一個字符串。此外,我必須傳遞多個參數給函數,我不能使用let result =「N」.withCString {dgeev_(UnsafeMutablePointer($ 0),UnsafeMutablePointer($ 0),& N,...)}之類的東西。請給我演示一下如何完成這個例子。
取決於C函數是採用'char *'還是'const char *',要麼是http://stackoverflow.com/questions/27876179/unsafemutablepointerint8-from-string-in-swift或http:// stackoverflow.com/questions/27063569/string-value-to-unsafepointeruint8-function-parameter-behavior應該解決你的問題。 –
感謝您的回答,但我仍然有一些問題。 u post的例子只有一個字符,但我有一個字符串。此外,我必須傳遞多個參數給函數,我不能使用'let result =「N」.withCString {UnsafeMutablePointer($ 0),UnsafeMutablePointer($ 0),&N,...)012ge} '。請給我演示一下如何完成這個例子。 –
相同的技術適用於(多個)字符串,但爲了您的方便,我添加了它作爲答案:) –