2016-01-28 68 views
-1

我有一個在C中的結構類型和swift從C定義創建一個結構指針var - 該部分工作正常。Swift鑄造unsafemutablepointer <MyStruct>到C void返回指針

我有一個C函數返回一個空指針指向同一類型的C結構。

問題是返回的C void指針不會傳遞給接收的swift結構指針。我無法弄清楚如何投射或轉換它。我錯過了什麼?

C頭

void* MyCFunc(int input); 
struct MyStruct 
{ 
    int ID; 
    int thisOne; 
    float thatOne; 
} MyStruct; 

SWIFT調用代碼

var ptr:UnsafePointer<MyStruct> 
ptr = MyCFunc(5)     //Error Here 

回答

1

看看這個 '自我解釋' 例如

struct MyStruct { 
    var myId: Int 
    var myDouble: Double 
} 

var myStruct = MyStruct(myId: 1, myDouble: 1.0) 

// this mimics the funcion which returns Void *myStruct 
var vptr = withUnsafeMutablePointer(&myStruct) { (pStruct) -> UnsafeMutablePointer<Void> in 
    return UnsafeMutablePointer<Void>(pStruct) 
} 
print(vptr) // 0x00000001079c7828 
// mimics mPtr = (MyStruct *) vptr 
let mPtr = UnsafeMutablePointer<MyStruct>(vptr) // UnsafeMutablePointer(0x10EE37838) 

mPtr.memory.myId = 10 
mPtr.memory.myDouble = 10.0 

print(myStruct) // MyStruct(myId: 10, myDouble: 10.0)