从Python传递的字符指针数组打印问题

1 投票
1 回答
1328 浏览
提问于 2025-04-16 09:56

我写的C代码运行得很好,但当我的Python代码试图把一个字符指针数组传给它时,就出现了问题。

我得到的输出是:

文件名是 python-file

另外三个字符串没有被打印出来。我是不是漏掉了什么?

C代码

#include <iostream>
#include "c_interface.h"

int foo(const char* file_name, const char** names) {
    std::cout << "The file_name is " << file_name << std::endl;
    while (*names) {
        std::cout << "The name is " << *names << std::endl;
        names++;
    }
    return 0;
}

/*
int main() {
    const char *c[] = {"123gh", "456443432", "789", 0};
    foo("hello", c);
    getchar();
}
*/

Python代码

#!c:/Python27/python.exe -u

from ctypes import *

name0 = "NAME0"
name1 = "NAME1"
name2 = "NAME2"

names = ((c_char_p * 1024) * 4)()
names[0].value = name0
names[1].value = name1
names[2].value = name2
names[3].value = 0

libc = CDLL("foo.dll")
libc.foo("python-file", names)

1 个回答

1

在使用和编译你的C++代码时,我只能重复我在上一个回答中提到的代码:

In [1]: import ctypes

In [2]: lib = ctypes.CDLL("libfoo.so.1.0")

In [3]: names = (ctypes.c_char_p*4)()

In [4]: names[0] = "NAME0"

In [5]: names[1] = "NAME1"

In [6]: names[2] = "NAME2"

In [7]: names[3] = 0

In [8]: lib.foo("whatever", names)
The file_name is whatever
The name is NAME0
The name is NAME1
The name is NAME2
Out[8]: 0

给你一个建议,打开你的Python/IPython命令行,执行你的代码行

names = ((c_char_p * 1024) * 4)()

...然后检查一下第一个元素 names[0] 的目录项,可以用 dir 命令来查看。或者,先试着访问一下它的值属性。

撰写回答