Python,从C库中获取字符串

标签 python c

我已经很多年没有使用 C 了,所以我一直在研究如何从一个简单的库中取回字符串并将其导入 Python。

测试.c

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

char * get_string() {

        char theString[]= "This is my test string!";

        char *myString = malloc ( sizeof(char) * (strlen(theString)) +1 );

        strcpy(myString, theString);

        return myString;
}

我使用以下代码编译代码:

gcc -Wall -O3 -shared test.c -o test.so

python.py

#!/usr/bin/env python

import ctypes

def main():
    string_lib = ctypes.cdll.LoadLibrary('test.so')
    myString = string_lib.get_string()
    print ctypes.c_char_p(myString).value

if __name__ == '__main__':
    main()

当我运行 Python 脚本时,我得到:

Segmentation fault: 11

如果我只打印结果,我会得到一个数值,我假设它是指针...我怎样才能让它工作?

谢谢!

最佳答案

问题是您使用的是 64 位 Python。这将截断返回的指针。

先声明restype:

 import ctypes

 def main():
     string_lib = ctypes.cdll.LoadLibrary('test.so')
     string_lib.get_string.restype = ctypes.c_char_p
     myString = string_lib.get_string()
     print myString

 if __name__ == '__main__':
     main()

关于Python,从C库中获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30287132/

相关文章:

Android 内核构建错误 : core_ctl. c - 取消引用指向不完整类型的指针

python - 在 python 中,我可以使用 tee 延迟生成迭代器的副本吗?

python - 如何检查requirements.txt文件中包含哪些包?

python - 我可以利用 Pyside clicked.connect 连接一个有参数的函数吗

Python:只接受特定的IP(套接字)

c - 为什么这段 C 代码会崩溃

c - 为什么 fopen() 无法识别我的文件名?

python - 我怎样才能登录这个页面并阅读它?

c++ - 为什么char * c 可以被赋值为字符串而不需要分配或引用?

c - 中间命令行界面