0

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!

2
  • Do you need the -fpic flag when you compile the c code? Commented May 17, 2015 at 13:05
  • @PaulRooney - Tried it now, same result. Commented May 17, 2015 at 13:08

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.