python调用c返回字符串_ctypes从c函数返回字符串

您的问题是问候语是在堆栈上分配的,但是当函数返回时堆栈会被破坏。您可以动态分配内存:#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")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值