Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a String from C to Python

I'm new to both C and Python, I'm trying to get the C function getText() into Python but all I'm getting are numbers

This is foo.c

#include <stdio.h>

const char * getText(void)
{
    return "world hello";
}
const char * getText2(void)
{
    return "hello world";
}

And this is my python code from the terminal

>>> import ctypes
>>> testlib = ctypes.CDLL('/home/user/dir/libfoo.so')
>>> testlib.getText()
743175865

I have already compiled the shared object and testing it with puts("Hello world") works as it appears in the terminal.

I'm sure I'm accessing the getText() wrongly from python but I don't know which one. Any suggestions or help would be appreciated

like image 635
K.Gibran Avatar asked Oct 19 '25 21:10

K.Gibran


1 Answers

There is an example of how to handle string return types in the ctypes documentation. Unless the foreign function returns and int, you need to set the return type for the foreign function with the .restype attribute. For your code:

import ctypes
testlib = ctypes.CDLL('/home/user/dir/libfoo.so')
testlib.getText.restype = testlib.getText2.restype = ctypes.c_char_p
print testlib.getText()
print testlib.getText2()

Output

world hello
hello world
like image 76
mhawke Avatar answered Oct 21 '25 10:10

mhawke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!