ctypes 在 OSX 上崩溃

2 投票
1 回答
1114 浏览
提问于 2025-04-17 16:17

我在Python中用ctypes创建了一个非常简单的C库绑定。它的功能就是接收一个字符串,然后返回一个字符串。

我是在Ubuntu系统上开发的,所有东西看起来都很好。可惜的是,在OSX系统上,完全相同的代码却失败了。我完全搞不懂为什么。

我整理了一个简单的例子,展示我遇到的问题。

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 个回答

4

你应该明确你函数的返回类型。具体来说,应该声明它为 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)

撰写回答