如何将项目插入到 c_char_p 数组中

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

我想把一个字符指针的数组传递给一个C语言的函数。

我参考了这个链接:http://docs.python.org/library/ctypes.html#arrays

我写了以下代码。

from ctypes import *

names = c_char_p * 4
# A 3 times for loop will be written here.
# The last array will assign to a null pointer.
# So that C function knows where is the end of the array.
names[0] = c_char_p('hello')

但是我遇到了以下错误。

类型错误:'_ctypes.PyCArrayType'对象不支持项赋值

有没有什么办法可以解决这个问题?我想要和

c_function(const char** array_of_string);

1 个回答

17

你所做的其实是创建了一个数组的类型,而不是一个真正的数组,所以基本上是这样的:

import ctypes
array_type = ctypes.c_char_p * 4
names = array_type()

然后你可以这样做:

names[0] = "foo"
names[1] = "bar"

...接着就可以用这个 names 数组作为参数来调用你的 C 函数。

撰写回答