I'd like to convert NSArray<NSInteger> or NSData to UnsafeMutablePointer<UInt8> for use with calling a native library. The native method in C is exposed as
typedef struct {
int64_t len;
uint8_t * _Nullable data;
} ByteBuffer;
int32_t pack(ByteBuffer request, ByteBuffer * _Nullable response, ExternError * _Nullable err);
This becomes in Swift
func pack(_ request: ByteBuffer, _ response: UnsafeMutablePointer<ByteBuffer>?, _ err: UnsafeMutablePointer<ExternError>?) -> Int32
// ByteBuffer
struct ByteBuffer {
var len: Int64
var data: UnsafeMutablePointer<UInt8>?
}
This method would be called from React Native, so my swift definition for the input method is
func pack(request: Array<NSInteger>, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void { }
I'm not making much progress, as I struggle understanding how swift works with pointers.
func pack(request: Array<NSInteger>, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
var req = ByteBuffer(len: Int64(request.count), data: nil)
req.data = UnsafeMutablePointer<UInt8>.allocate(capacity: request.count)
let ptr = UnsafePointer<UInt8>([1, 2, 3])
req.data?.assign(from: ptr, count: request.count)
pack(req, _, _)
}
I'm not sure if I'm on the right track here, I would appreciate help in any direction. The code above also produces a warning Initialization of 'UnsafePointer<UInt8>' results in a dangling pointer.
Would it be easier to just write this in Objective C instead?