2017-06-21 43 views
1

我一個C API定義與const char *與返回一個char *,我試圖找到做任務的最佳方式的功能結構的工作。分配UnsafeMutablePointer值UnsafePointer沒有unsafeBitCast

有沒有辦法做到這一點,而無需使用unsafeBitCast?如果我不把投那麼我得到這個錯誤:

Cannot assign value of type 'UnsafeMutablePointer<pchar>' 
(aka 'UnsafeMutablePointer<UInt8>') 
to type 'UnsafePointer<pchar>!' 
(aka 'ImplicitlyUnwrappedOptional<UnsafePointer<UInt8>>') 

此外,將pairPtr低於使用對()分配一個對結構堆棧中的初始化初始化堆上,因爲這個對分配對於結構必須被清零的情況似乎效率低下。

下面是示例代碼:

C庫頭(最小化來演示該問題):

#ifndef __PAIR_INCLUDE__ 
#define __PAIR_INCLUDE__ 

typedef unsigned char pchar; 

pchar* 
pstrdup(const pchar* str); 

typedef struct _pair { 
    const pchar* left; 
    const pchar* right; 
} pair; 

#endif // __PAIR_INCLUDE__ 

我的銀行代碼:

import pair 

let leftVal = pstrdup("left") 
let rightVal = pstrdup("right") 

let pairPtr = UnsafeMutablePointer<pair>.allocate(capacity: 1) 
pairPtr.initialize(to: pair()) 

// Seems like there should be a better way to handle this: 
pairPtr.pointee.left = unsafeBitCast(leftVal, to: UnsafePointer<pchar>.self) 
pairPtr.pointee.right = unsafeBitCast(rightVal, to: UnsafePointer<pchar>.self) 

C代碼:

#include "pair.h" 
#include <string.h> 

pchar* 
pstrdup(const pchar* str) { 
    return strdup(str); 
} 

該模塊Ë定義:

module pair [extern_c] { 
    header "pair.h" 
    export * 
} 
+0

爲什麼不簡單'讓p =對(左:leftVal,right:rightVal)'?我不明白爲什麼應該需要unsafeBitCast,也許我忽略了一些東西? –

+0

這會工作,但對於真正的結構有20個屬性,我只值分配給約5是否存在的情況下直接投至指定的簡單方法? – Julian

+0

如果唯一的問題是不同的可變性,那麼'p.left = UnsafePointer(leftVal)'應該可以工作。 –

回答

1

可以使用的UnsafePointer

/// Creates an immutable typed pointer referencing the same memory as the 
/// given mutable pointer. 
/// 
/// - Parameter other: The pointer to convert. 
public init(_ other: UnsafeMutablePointer<Pointee>) 

初始創建從UnsafeMutablePtr<T>UnsafePointer<T>只需用

let ptr = UnsafePointer(mptr) 

。在你的情況下,例如將

p.left = UnsafePointer(leftVal)