您的问题是问候语是在堆栈上分配的,但是当函数返回时堆栈会被破坏。您可以动态分配内存:#include
#include
#include
const char* hello(char* name) {
char* greeting = malloc(100);
snprintf("Hello, %s!\n", 100, name)
printf("%s\n", greeting);
return greeting;
}
但这只是战斗的一部分,因为现在你有内存泄漏。您可以用另一个对free()的ctypes调用来插入它。
……或者更好的方法是阅读到python的官方C绑定(python 2.x位于http://docs.python.org/2/c-api/,python 3.x位于http://docs.python.org/3/c-api/)。让您的C函数创建一个python字符串对象并将其返回。它将被python自动垃圾回收。既然你在写C语言,你就不必玩C语言游戏了。
…编辑。。
我没有编译和测试,但我认为这个.py可以工作:import ctypes
# define the interface
hello = ctypes.cdll.LoadLibrary('./hello.so')
# find lib on linux or windows
libc = ctypes.CDLL(ctypes.util.find_library('c'))
# declare the functions we use
hello.hello.argtypes = (ctypes.c_char_p,)
hello.hello.restype = ctypes.c_char_p
libc.free.argtypes = (ctypes.c_void_p,)
# wrap hello to make sure the free is done
def hello(name):
_result = hello.hello(name)
result = _result.value
libc.free(_result)
return result
# do the deed
print hello("Frank")