2017-04-13 290 views
0

我有以下代碼不會編譯,因爲XCode不會讓我在我的C++代碼中將一個NSArray元素轉換爲指針。 XCode給出的錯誤是:Assigning to 'UInt8 *' from incompatible type 'id'如何將元素從Swift中的[UnsafeMutablePointer <UInt8>]轉換爲C++中的UInt8 *

我該如何將類型[UnsafeMutablePointer<UInt8>]的數組從Swift傳遞到Objective-C++?

預先感謝您

objcfunc.h

+ (void) call: (NSArray *) arr; 

objcfunc.mm

+ (void) call: (NSArray *) arr { 
UInt8 *buffer; 
buffer = (UInt8 *) arr[0]; // doesn't work, XCode throws an error 
unsigned char *image; 
image = (unsigned char *) buffer; 
processImage(image); // C++ function 
} 

斯威夫特

var arr: [UnsafeMutablePointer<UInt8>] = [] 
arr.append(someImage) 
objcfunc.call(swiftArray: arr) 

但是,如果我不使用數組和直接傳遞指針,代碼工作正常:

objcfunc.h

+ (void) callSingle: (UInt8 *) buf; 

objcfunc.mm

+(void) callSingle: (UInt8 *) buf { 
unsigned char *image; 
image = (unsigned char *) buf; // works fine 
processImage(image); 
} 

Swift

let x: UnsafeMutablePointer<UInt8> buf; 
// initialize buf 
objcfunc.callSingle(buf); 

回答

0

NSArray是Objective-C對象的數組。所以,你需要傳遞一些橋接到Objective-C類型的類型的實例。我不確定斯威夫特的UnsafeMutablePointer結構是橋接的。

因爲在這種情況下,你是通過圖像緩衝區的數組(如果我理解正確的),你可能要考慮使用NSDataData,而不是UnsafeMutablePointer<UInt8>每個圖像緩衝區。這些類型專門用於處理字節數組,這是一個圖像緩衝區;看到 https://developer.apple.com/reference/foundation/nsdatahttps://developer.apple.com/reference/foundation/data

下面是如何可以使用DataNSData做一個人爲的例子:

Objective-C的實現:

@implementation MyObjC 

+ (void) call: (NSArray *) arr { 
    NSData * data1 = arr[0]; 
    UInt8 * bytes1 = (UInt8 *)data1.bytes; 
    bytes1[0] = 222; 
} 

@end 

斯威夫特:

var arr: [UnsafeMutablePointer<UInt8>] = [] 

// This is just an example; I'm sure that actual initialization of someImage is more sophisticated. 
var someImage = UnsafeMutablePointer<UInt8>.allocate(capacity: 3) 
someImage[0] = 1 
someImage[1] = 12 
someImage[2] = 123 

// Create a Data instance; we need to know the size of the image buffer. 
var data = Data(bytesNoCopy: someImage, count: 3, deallocator: .none) 

var arrData = [data] // For demonstration purposes, this is just a single element array 
MyObjC.call(arrData) // You may need to also pass an array of image buffer sizes. 

print("After the call: \(someImage[0])") 
相關問題