将字符串从 C 返回到 Python

Returning a String from C to Python

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

这是foo.c

#include <stdio.h>

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 中有一个如何处理字符串 return 类型的示例。除非是外函数returns和int,需要用.restype属性为外函数设置return类型。对于您的代码:

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

你的 foo.c return 本地数组你必须 return 指向使用 malloc 动态声明的数组的指针。

const char * getText(char* name)
{    
  char hello[] = "world hello";
  char *var1 = malloc ( sizeof(char) * ( strlen(name) + strlen(hello) + 1 ) );
  if( var1 == NULL) exit(1);
   strcpy( var1 , hello);
   strcat(var1, name);    
   return var1;
 }