Search code examples
swiftpointersinteroppointer-to-pointer

Call native method from Swift that has uint8_t ** as output parameter


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?


Solution

  • 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)