pythoncsegmentation-faultctypeslanguage-binding

ctypes segfault on OSX only


I created a very simple C library binding in Python using ctypes. All it does is accept a string and return a string.

I did the development on Ubuntu, and everything looked fine. Unfortunately, on OSX the exact same code fails. I'm completely stumped.

I've put together a minimal case showing the issue I'm having.

main.py

import ctypes

# Compile for:
#   Linux: `gcc -fPIC -shared hello.c -o hello.so`
#   OSX:   `gcc -shared hello.c -o hello.so`
lib = ctypes.cdll.LoadLibrary('./hello.so')

# Call the library
ptr = lib.hello("Frank")
data = ctypes.c_char_p(ptr).value # segfault here on OSX only
lib.free_response(ptr)

# Prove it worked
print data

hello.c

#include <stdlib.h>
#include <string.h>

// This is the actual binding call.
char* hello(char* name) {
    char* response = malloc(sizeof(char) * 100);
    strcpy(response, "Hello, ");
    strcat(response, name);
    strcat(response, "!\n");
    return response;
}

// This frees the response memory and must be called by the binding.
void free_response(char *ptr) { free(ptr); }

Solution

  • You should specify the return type of your function. Specifically, declare it to be ctypes.POINTER(ctypes.c_char).

    import ctypes
    
    lib = ctypes.CDLL('./hello.so')    
    lib.hello.restype = ctypes.POINTER(ctypes.c_char)
    
    ptr = lib.hello("Frank")
    print repr(ctypes.cast(ptr, ctypes.c_char_p).value)
    lib.free_response(ptr)