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

时间:2011-01-14 02:48:41

标签: c++ python c ctypes

我的以下C代码工作得很好,直到我的Python代码试图传递一个char指针数组。

我获得的输出是

  

file_name是python-file

另外3个字符串未打印出来。我错过了什么?

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 个答案:

答案 0 :(得分: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 shell,执行你的行

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

...并使用names[0]检查第一个元素dir目录条目。或者,尝试访问值属性以开始。