python c语言 返回字符串,从C返回字符串到Python

我是C和Python的新手,我正在尝试将C函数getText()放入Python,但我得到的只是数字

这是foo.c

#include

const char * getText(void)

{

return "world hello";

}

const char * getText2(void)

{

return "hello world";

}

这是我来自终端的python代码

>>> import ctypes

>>> testlib = ctypes.CDLL('/home/user/dir/libfoo.so')

>>> testlib.getText()

743175865

我已经编译了共享库,并使用puts(“ Hello world”)对其进行了测试,就像它出现在终端上一样.

我确定我从python错误地访问了getText(),但是我不知道哪个.任何建议或帮助,将不胜感激

解决方法:

在ctypes documentation中有一个如何处理字符串返回类型的示例.除非外部函数返回和int,否则您需要使用.restype属性设置外部函数的返回类型.对于您的代码:

import ctypes

testlib = ctypes.CDLL('/home/user/dir/libfoo.so')

testlib.getText.restype = testlib.getText2.restype = ctypes.c_char_p

print testlib.getText()

print testlib.getText2()

输出量

world hello

hello world

标签:python-2-7,shared-libraries,c-3,python

来源: https://codeday.me/bug/20191119/2035576.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值