【问题标题】:How to cast element from [UnsafeMutablePointer<UInt8>] in Swift to UInt8 * in C++如何将元素从 Swift 中的 [UnsafeMutablePointer<UInt8>] 转换为 C++ 中的 UInt8 *
【发布时间】:2017-04-13 00:57:45
【问题描述】:

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

我应该如何将 [UnsafeMutablePointer&lt;UInt8&gt;] 类型的数组从 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);

【问题讨论】:

    标签: c++ ios objective-c swift xcode


    【解决方案1】:

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

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

    这是一个人为的示例,说明如何使用 Data 和 NSData 完成此操作:

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

    【讨论】:

      猜你喜欢
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多