2017-09-23 4 views
2

나는이 소스 코드를 변환하려고 해요에 UnsafeMutableRawPointer의 값을 변환 할 수 없습니다,이 BluetoothDeviceAddress

let deviceAddress: BluetoothDeviceAddress = malloc(sizeof(BluetoothDeviceAddress)) 

을하지만 발견 스위프트 3/4, sizeof는 더 이상 사용되지 않지만 내 오류가 아닙니다. Xcode는 다음을 반환합니다.

" 'UnsafeMutableRawPointer!'유형의 값을 변환 할 수 없습니다. 지정된 유형 'BluetoothDeviceAddress' "

malloc(MemoryLayout<BluetoothDeviceAddress>.size)으로 변경하려고 시도했지만 여전히 동일한 오류가 발생했습니다.

편집 :

self.selectedDevice = IOBluetoothDevice(address: deviceAddress) 
: (selectedDevice는 IOBluetoothDevice을위한 VAR입니다) MartinR에 의해 코멘트에서 제안으로 , 나는 let deviceAddress = BluetoothDeviceAddress() 로 변경 시도하지만 내가 IOBluetoothDevice를 초기화 할 때 다음, 나는 여전히 오류가

오류 : 'BluetoothDeviceAddress'유형의 값을 예상되는 인수 유형 'UnsafePointer!'로 변환 할 수 없습니다.

보다도,

앙투안

+0

* 메모리를 할당해야하는 이유는 무엇입니까? 그냥'let/var deviceAddress = BluetoothDeviceAddress()'가 아닌가? –

+0

@MartinR 작동하지 않습니다. 제 편집 참조 – Antoine

답변

1

는 직접적인 질문에 대답하는 대신

let ptr = malloc(MemoryLayout<BluetoothDeviceAddress>.size)! // Assuming that the allocation does not fail 
let deviceAddressPtr = ptr.bindMemory(to: BluetoothDeviceAddress.self, capacity: 1) 
deviceAddressPtr.initialize(to: BluetoothDeviceAddress()) 
// Use deviceAddressPtr.pointee to access pointed-to memory ... 

let selectedDevice = IOBluetoothDevice(address: deviceAddressPtr) 
// ... 

deviceAddressPtr.deinitialize(count: 1) 
free(ptr) 

: bindMemory()와 스위프트의 "바인딩"을 수행라고 원시 포인터에서 입력 포인터를 취득 malloc/free 중 하나는 할당/해제 메소드 을 Unsafe(Mutable)Pointer으로 Swift에서 사용합니다.

let deviceAddressPtr = UnsafeMutablePointer<BluetoothDeviceAddress>.allocate(capacity: 1) 
deviceAddressPtr.initialize(to: BluetoothDeviceAddress()) 
// Use deviceAddressPtr.pointee to access pointed-to memory ... 

let selectedDevice = IOBluetoothDevice(address: deviceAddressPtr) 
// ... 

deviceAddressPtr.deinitialize(count: 1) 
deviceAddressPtr.deallocate(capacity: 1) 

원시 포인터 및 바인딩에 대한 자세한 내용은 SE-0107 UnsafeRawPointer API 을 참조하십시오.

그러나는 유형 직접 값을 생성하고 &와 입출력 식으로 그 통과하는 것이 용이하다. 예 :

var deviceAddress = BluetoothDeviceAddress() 
// ... 

let selectedDevice = IOBluetoothDevice(address: &deviceAddress) 
// ... 
+0

놀랍습니다. 완벽하게 작동합니다. – Antoine