如何将元素从 Swift 中的 [UnsafeMutablePointer<UInt8>] 转换为 C++ 中的 UInt8 *
How to cast element from [UnsafeMutablePointer<UInt8>] in Swift to UInt8 * in C++
我有以下代码无法编译,因为 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
结构是否桥接。
因为在这种情况下,您正在传递图像缓冲区数组(如果我正确理解(,您可能需要考虑使用 NSData
或 Data
,而不是为每个图像缓冲区使用 UnsafeMutablePointer<UInt8>
。 这些类型专门用于处理字节数组,这就是图像缓冲区;看https://developer.apple.com/reference/foundation/nsdata 和https://developer.apple.com/reference/foundation/data
下面是如何使用Data
和NSData
完成此操作的人为示例:
目标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])")
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- .cpp和.h文件中的模板专用化声明
- 反向给定链表中的K节点
- 正在查找文档以获得PS4平台的C++中的设备信息
- enum是C++中的宏变量还是整数变量
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 将字符串存储在c++中的稳定内存中
- 文本文件中的单词链表
- 递归函数计算序列中的平方和(并输出过程)
- 如何从C++中的依赖类型中获得它所依赖的类型
- C++中的"inline"关键字
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 用C++中的一个变量定义一个常量
- vector.resize()中的分配错误
- 使用指针从C++中的数组中获取最大值
- arr[-1]在c++中的奇怪行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 如何将元素从 Swift 中的 [UnsafeMutablePointer<UInt8>] 转换为 C++ 中的 UInt8 *
- 我如何将uint8_t (SDL中的Uint8)转换为字符串