【问题标题】:Problem in printing array of char pointer passing from Python打印从 Python 传递的 char 指针数组时出现问题
【发布时间】:2011-01-14 02:48:41
【问题描述】:

我的以下 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)

【问题讨论】:

    标签: c++ python c ctypes


    【解决方案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。或者,尝试访问 value 属性作为开始。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 2012-10-29
      • 2020-12-25
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多