Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieve a `char *` returned from C function exported from .so in Python

Tags:

python

c

I got a liba.so containing a function say_hi(),

char *say_hi()
{
    return "hello, world";
}

In Python, I accessed liba.so via ctypes,

>>>liba = ctypes.CDLL("./liba.so")
>>>liba.say_hi()
16422018

How can I retrieve the string "hello, world" returned by liba.say_hi() in Python?

PS

Besides restype, any other way?

like image 247
Alcott Avatar asked Oct 13 '25 10:10

Alcott


2 Answers

Does this answer your question?

http://docs.python.org/library/ctypes.html#return-types

like image 164
Matimus Avatar answered Oct 14 '25 23:10

Matimus


The docs of Python ctypes-modules offers type-casting functions. Eg. c_char_p:

Represents the C char * datatype when it points to a zero-terminated string. For a general character pointer that may also point to binary data, POINTER(c_char) must be used. The constructor accepts an integer address, or a bytes object.

So try this:

ctypes.c_char_p( liba.say_hi() )

PS: It builds immutable strings. For mutable ones look at create_string_buffer There are also some self-descriptive exameples on the page.

like image 25
Andrew D. Avatar answered Oct 15 '25 00:10

Andrew D.