Matt
Matt

Reputation: 87

Cffi and char** as an argument

I have a following code in Python, using cffi:

from cffi import FFI

ffi = FFI()
ffi.cdef("int somefunc(char** data);")

lib = ffi.dlopen("somelib")

Now, I want to call the somefunc with char** and get the data to Python. somefunc actually fills the data, so:

data = ffi.new("char**", ffi.NULL)
lib.somefunc(data)

So how am I now supposed to get the result from the data variable to a Python string? Any ideas?

Thank you!

Upvotes: 1

Views: 1220

Answers (1)

Armin Rigo
Armin Rigo

Reputation: 12900

data[0] or data[n] gives you the n-th item in the array. (If there is only one string, that will be data[0]; I think it is the case based on details in your question.) That's still a char *, but you can interpret like a null-terminated byte string using ffi.string(data[0]). As usual, you might then have to decode that byte string to a normal unicode string using the right encoding.

The full program looks like:

from cffi import FFI

ffi = FFI()
ffi.cdef("int somefunc(char** data);")

lib = ffi.dlopen("somelib")
data = ffi.new("char**", ffi.NULL)
lib.somefunc(data)

value = ffi.string(data[0])

Upvotes: 1

Related Questions