我使用 ctypes 在 Python 中创建了一个非常简单的 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); }
您应该指定函数的返回类型。具体来说,声明为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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)