ctypes segfault on OSX only

瘦欲@ 提交于 2021-01-28 02:51:04

问题


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); }

回答1:


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)


来源:https://stackoverflow.com/questions/14944367/ctypes-segfault-on-osx-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!