-1

i use an api in swift that provide me a function to send data to some destination ,the function has a parameter of type UnsafeMutablePointer < astruct >. astruct is a structure and has three variable, first one is the data , that is of type UnsafePointer < Uint8 > , second one is bytes to send of type uint32 and destination is third one.

now the question is how to work with this function, how to give these variables to call the function and init the struct.

what i have as data to send is an array [0xf0,0xf7,0x03,0x01]. what should i do now? can't accept the array as the data in astruct, it should be UnsafePointer, i read the documentation on UnsafePointer but i dont get it that well, can some one please help me??

// swift api

func senddata (_ req: UnsafeMutablePointer < astruct >) -> OSStatus

struct astruct {
  var data : UnsafePointer < UInt8 > 
  var bytestosend : UInt32
  var destination : destination
}

var array : [UInt8] = [0xf0,0xf7,0x03,0x01]
var st = astruct(data : array , bytestosend : UInt32(array.count) , destination: dest)
senddata ( st )

how to do the unsafe pointe thing?

Gereon
  • 14,827
  • 4
  • 36
  • 62
  • 1
    As a courtesy to potential answerers, please *format* the code properly, and copy/paste the *exact* code: `Func` should be `func`, `var array : Uint8` should be `var array : [UInt8]` and so on. – Martin R Dec 03 '19 at 08:03

1 Answers1

1

Use .withUnsafeBufferPointer to get to the array's data, and use & to pass the struct to your senddata function:

func senddata(_ req: UnsafeMutablePointer<Astruct>) -> OSStatus? {
    // ...
}

struct Astruct {
  let data: UnsafePointer<UInt8>
  let bytestosend: UInt32
  let destination: destination
}

var array: [UInt8] = [ 0xf0, 0xf7, 0x03, 0x01 ]

array.withUnsafeBufferPointer { ptr in
    guard let data = ptr.baseAddress else {
        return
    }
    var st = Astruct(data: data, bytestosend: UInt32(array.count), destination: dest)
    senddata(&st)
}
Gereon
  • 14,827
  • 4
  • 36
  • 62
  • Better use `withUnsafeBufferPointer`, then you don't need the rebinding. – Martin R Dec 04 '19 at 09:24
  • One final note: `baseAddress != nil` is *guaranteed* if the buffer is not empty. – Martin R Dec 04 '19 at 12:42
  • thank you sir for your answer ,but i get this error : Thread 10: EXC_BAD_ACCESS (code=2, address=0x280a54500) – user8058965 Dec 05 '19 at 05:23
  • do i need to deallocate ?? and what about the senddata function ? the req parameter is of type UnsafeMutablePointer ?? do i need to do same thing for that as well? – user8058965 Dec 05 '19 at 05:27
  • this is where i want to use this code : https://stackoverflow.com/questions/57950463/can-not-compile-the-midi-system-exclusive – user8058965 Dec 05 '19 at 05:30