gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:07:05 25 4
gpt4 key购买 nike

我的以下 C 代码运行良好,直到我的 Python 代码试图将一个 char 指针数组传递给它。

我得到的输出是

The file_name is 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++代码,我只能重复我在上一个答案中已经说过的代码:

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 属性作为开始。

关于c++ - 打印从 Python 传递的 char 指针数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4687520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com