2017-04-13 292 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])") 
相关问题