【问题标题】:Returning a String from C to Python将字符串从 C 返回到 Python
【发布时间】:2015-12-02 05:38:11
【问题描述】:

我是 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(),但我不知道是哪一个。任何建议或帮助将不胜感激

【问题讨论】:

    标签: python c python-2.7 shared-libraries


    【解决方案1】:

    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()
    

    输出

    世界你好 你好世界

    【讨论】:

      【解决方案2】:

      您的 foo.c 返回本地数组,而您必须使用 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;
       }
      

      【讨论】:

      • 没有。由于返回的字符串被声明为字面量,它们将存在于全局地址空间的字符串表中,因此它们将在函数返回后可以访问。
      猜你喜欢
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-10
      • 2021-09-05
      • 2021-08-04
      • 2012-01-14
      • 2021-12-01
      相关资源
      最近更新 更多