2

我使用 ctypes 在 Python 中创建了一个非常简单的 C 库绑定。它所做的只是接受一个字符串并返回一个字符串。

我在 Ubuntu 上进行了开发,一切看起来都很好。不幸的是,在 OSX 上完全相同的代码失败了。我完全被难住了。

我已经整理了一个最小的案例来显示我遇到的问题。

主文件

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

你好ç

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

1 回答 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)
于 2013-02-18T20:17:00.007 回答