Ctypes create_string_buffer 引发 TypeError(init)

0 投票
1 回答
2163 浏览
提问于 2025-04-18 04:06

我正在尝试通过ctypes把一个Python字符串传递给一个C语言的函数(DLL)。这个函数需要一个const char*类型的参数。我使用了create_string_buffer,但出现了错误:

raise TypeError(init) TypeError:

我的Python代码非常简单:

testUpdate = myDll['testUpdate']
def testUpdate(Path):
    p_path = ctypes.create_string_buffer(Path)
    print ctypes.sizeof(p_path), repr(p_path.raw)
    print repr(p_path.value)

    testUpdate(p_path)
    testUpdate.restype = ctypes.c_char

而我的C代码更简单:

char testUpdate(const char* softwareToolsPath){
     char p;
     p = *softwareToolsPath;
     return p;

}

我看到过这个帖子:

create_string_buffer抛出错误TypeError: 期望str/bytes而不是str实例

但这对我没有帮助。有人能帮忙吗?

我使用的是Python 2.7。

为了避免混淆,我只是想用Python给一个DLL提供一个路径。这个DLL会打开路径指向的文件并进行处理。所以我只是想为一个现有的C函数写一个小的封装。

1 个回答

1

我有点困惑。testUpdate(p_path)这个函数是要调用一个C语言的函数吗?看起来它实际上是在递归调用Python代码(而且参数类型不对)。你可以试着给这个Python函数换个名字。

顺便说一下,你的C代码有问题。我想你想要的是

char * testUpdate(const char * softwareToolsPath) {
    char * p;
    p = softwareToolsPath;
    return p;
}

撰写回答