Reputation: 377
I haven't worked with C for many many years now so I'm stuck on how I can get a string back from a simple library and into Python.
test.c
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char * get_string() {
char theString[]= "This is my test string!";
char *myString = malloc ( sizeof(char) * (strlen(theString)) +1 );
strcpy(myString, theString);
return myString;
}
I compile the code using:
gcc -Wall -O3 -shared test.c -o test.so
python.py
#!/usr/bin/env python
import ctypes
def main():
string_lib = ctypes.cdll.LoadLibrary('test.so')
myString = string_lib.get_string()
print ctypes.c_char_p(myString).value
if __name__ == '__main__':
main()
When I run the Python script I get:
Segmentation fault: 11
if I just print the result I get a numeric value which I assume is the pointer... How can I make it work?
Thanks!
Upvotes: 0
Views: 1082
Reputation: 6395
The problem is that you are using 64 bit Python. This will truncate the returned pointer.
Declare the restype first:
import ctypes
def main():
string_lib = ctypes.cdll.LoadLibrary('test.so')
string_lib.get_string.restype = ctypes.c_char_p
myString = string_lib.get_string()
print myString
if __name__ == '__main__':
main()
Upvotes: 2