swift - How to create a UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<Int8>>> -
i'm working c api swift , 1 of methods need call need give a
unsafemutablepointer<unsafemutablepointer<unsafemutablepointer<int8>>>
more info:
swift interface:
public func presage_predict(prsg: presage_t, _ result: unsafemutablepointer<unsafemutablepointer<unsafemutablepointer<int8>>>) -> presage_error_code_t
original c:
presage_error_code_t presage_predict(presage_t prsg, char*** result);
generally, if function takes unsafepointer<t>
parameter can pass variable of type t
in "inout" parameter &
. in case, t
is
unsafemutablepointer<unsafemutablepointer<int8>>
which swift mapping of char **
. can call c function as
var prediction : unsafemutablepointer<unsafemutablepointer<int8>> = nil if presage_predict(prsg, &prediction) == presage_ok { ... }
from documentation , sample code of presage library understand allocates array of strings , assigns address of array variable pointed prediction
. avoid memory leak, these strings have released
presage_free_string_array(prediction)
to demonstrate works, have taken first part of demo code @ presage_c_demo.c , translated swift:
// duplicate c strings avoid premature deallocation: let past = strdup("did not sa") let future = strdup("") func get_past_stream(arg: unsafemutablepointer<void>) -> unsafepointer<int8> { return unsafepointer(past) } func get_future_stream(arg: unsafemutablepointer<void>) -> unsafepointer<int8> { return unsafepointer(future) } var prsg = presage_t() presage_new(get_past_stream, nil, get_future_stream, nil, &prsg) var prediction : unsafemutablepointer<unsafemutablepointer<int8>> = nil if presage_predict(prsg, &prediction) == presage_ok { var = 0; prediction[i] != nil; i++ { // convert c string swift `string`: let pred = string.fromcstring(prediction[i])! print ("prediction[\(i)]: \(pred)") } presage_free_string_array(prediction) } free(past) free(future)
this worked , produced output
prediction[0]: prediction[1]: said prediction[2]: savages prediction[3]: saw prediction[4]: sat prediction[5]: same
Comments
Post a Comment