简体   繁体   中英

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

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?

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.

So try this:

ctypes.c_char_p( liba.say_hi() )

It builds immutable strings. 它构建不可变的字符串。 For mutable ones look at create_string_buffer There are also some self-descriptive exameples on the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM