1

I have a C method with the interface

size_t foo(uint8_t ** output)

This gets imported to Swift as

func foo(_ output: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>>) -> Int

How can I call this method from Swift?

Etan
  • 17,014
  • 17
  • 89
  • 148

1 Answers1

1

Assuming that foo() allocates an uint8_t array, puts the address into the memory location pointed to by output, and returns the size of the allocated array, you can use it from Swift like this

var output : UnsafeMutablePointer<UInt8> = nil
let size = foo(&output)
for i in 0 ..< size {
    println(output[i])
}

You will also have to decide who is responsible for releasing the allocated memory. If the foo() functions allocates it using malloc() then you can release it from Swift with

free(output)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Isn't foo's parameter pointer to a pointer, instead of pointer to UInt8 ? – Dejan Skledar May 15 '15 at 08:22
  • @DejanSkledar: `var output : UnsafeMutablePointer` is the Swift equivalent of a pointer to UInt8. It is passed as "inout parameter" `&output` to `foo()`, which is the Swift equivalent of passing the address of a variable. – Roughly speaking: `output` is a pointer to UInt8 and `&output` is a pointer to a pointer to UInt8. – Martin R May 15 '15 at 08:23
  • yes, but UnsafeMutablePointer> is in Swift equivalent of a pointer to an array of UInt8's , right? – Dejan Skledar May 15 '15 at 08:26
  • @DejanSkledar: No, `UnsafeMutablePointer>` is a pointer to a pointer. – I have tested the above code and it works as expected (if my assumptions about what foo() does are correct). – Martin R May 15 '15 at 08:27
  • I thought that foo() takes a pointer to an array, but anyway, it should work both ways. – Dejan Skledar May 15 '15 at 08:31