Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何直接访问Python列表的指针以传递给C函数?_Python_Cython_Ctypes - Fatal编程技术网

如何直接访问Python列表的指针以传递给C函数?

如何直接访问Python列表的指针以传递给C函数?,python,cython,ctypes,Python,Cython,Ctypes,我已经编写了一个名为SortInPlace的C函数,它对整数数组进行排序。现在我想从Python中调用它。以下是我的代码的核心: def sort_in_place(vs): buffer = (c_void_p * len(vs))(*vs) lib.SortInPlace.argtypes = [c_void_p] lib.SortInPlace.restype = None lib.SortInPlace(buffer) print "buffer:

我已经编写了一个名为
SortInPlace
的C函数,它对整数数组进行排序。现在我想从Python中调用它。以下是我的代码的核心:

def sort_in_place(vs):
    buffer = (c_void_p * len(vs))(*vs)
    lib.SortInPlace.argtypes = [c_void_p]
    lib.SortInPlace.restype = None
    lib.SortInPlace(buffer)
    print "buffer: ", buffer

vs = [3,2,1]
sort_in_place(vs)
print "vs: ", vs
然而,结果是

buffer: 1,2,3
vs: 3,2,1
我打印了
buffer
vs
地址,这表明它们的内存地址不同。因此,
buffer
被就地排序,但
vs
未被触及

我还尝试使用
array
通过以下方式将
vs
转换为指针:

from array import array
a = array('l',vs)

# however, their addresses are also different
print hex(id(vs))
print hex(a.buffer_info()[0])

在这两种情况下,原始的
vs
总是复制到新的内存缓冲区中。我的问题是:如何从Python列表对象的地址直接创建缓冲区而不进行复制?

您不能。有关如何处理此类案件,请参见示例。因为列表中的数据不是int值的连续数组。
buffer=(c\u void\u p*len(vs))(*vs)
用于复制数据。调用
lib.SortInPlace(buffer)
后,是否可以将值写回
vs
?这是一个解决办法。@RockSportRock这是我希望避免的,因为它可能效率低下。@ead我明白了。这太可悲了……您几乎可以肯定地从数组(而不是列表)中获得一个ctypes指针,然后修改该数组中的数据