如何将元素从 Swift 中的 [UnsafeMutablePointer<UInt8>] 转换为 C++ 中的 UInt8 *

How to cast element from [UnsafeMutablePointer<UInt8>] in Swift to UInt8 * in C++

本文关键字:UInt8 中的 gt 转换 C++ 元素 Swift UnsafeMutablePointer lt      更新时间:2023-10-16

我有以下代码无法编译,因为 XCode 不允许我将 NSArray 元素转换为C++代码中的指针。XCode 给出的错误是:Assigning to 'UInt8 *' from incompatible type 'id'

我应该如何将 [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);
}

迅速

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

NSArray是一个Objective-C对象的数组。 因此,您需要传递桥接到Objective-C类型的类型实例数组。 我不确定 Swift 的 UnsafeMutablePointer 结构是否桥接。

因为在这种情况下,您正在传递图像缓冲区数组(如果我正确理解(,您可能需要考虑使用 NSDataData ,而不是为每个图像缓冲区使用 UnsafeMutablePointer<UInt8>。 这些类型专门用于处理字节数组,这就是图像缓冲区;看https://developer.apple.com/reference/foundation/nsdata 和https://developer.apple.com/reference/foundation/data

下面是如何使用DataNSData完成此操作的人为示例:

目标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])")