python - C 方法通过 ctypes 将字符串返回给 Python

标签 python c ctypes

几年前,我必须为 C 库创建一个 Python 包装器。我对 C 的了解非常有限,但我设法创建了所需的内容。 突然,一种方法开始引起问题,我唯一的猜测是它必须对 python 更新执行某些操作。

无论如何,我有以下 C 代码:

const char * myFunction()
{
    return "My String";
}

DLL_EXPORT const char*
test()
{
    return myFunction();
}

在我的 Python 包装器中使用以下方法调用:

def test(self):
        ret = self.lib.test()

        return c_char_p(ret).value

如前所述,此方法运行良好,尽管我不太确定为什么考虑到我最近在尝试修复它时发现的情况。

目前,当我调用方法 test() 时,我从 python 中收到“段错误”。

使用此线程:

ctypes return a string from c function

When to use malloc for char pointers

我设法修复了我的代码,现在看起来像这样,c:

const char * myFunction()
{
    return "My String";
}

DLL_EXPORT const char*
test()
{
    const char* st = myFunction();
    char *bar = _strdup(st);

    return bar;
}

Python 代码保持不变。如前所述,我对 C 的了解非常有限,因此很少有问题:

  1. 知道为什么旧的实现正在运行并突然停止了吗?是否有一些 Python 更新可能会影响它?
  2. 为什么在我的 c test() 函数中我必须执行 _strdup(st) 并返回 bar 而不是简单地返回 st?

最佳答案

您使用的是 64 位 Python 吗? self.lib.test 的返回类型默认为 32 位的 c_int。如果指针是 64 位,则将截断指针。 您可能只是在代码更改中很幸运,_strdup 位于内存中的 4GB 以下。

如果您声明:

self.lib.test.restype = c_char_p

那么这应该可以工作:

def test(self):
    ret = self.lib.test()
    return ret.value

关于python - C 方法通过 ctypes 将字符串返回给 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49208498/

相关文章:

c# - 在 python 中使用 ctypes 访问 C# dll 的方法

python - 为什么可以在 python 3 中使用 ctypes 修改不可变字节对象?

python - 如何在Python中创建空的C类型数组(或只是一个NULL值)?

python - 像素/数组位置到 lat long gdal Python

python - nlargest(2) 在行级别检索列名称和相等值

c - Malloc ~ 段错误 C

c - 从 char * 到 int 的类型转换

python - 在列表中查找递增数字组

python - 有没有办法在 BeautifulSoup 中查找不包含特定类的标签?

c - 摆脱编译一些语句集