如何用数字指针对于ctypes python调用?

2024-09-23 20:24:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何使用ndpointer来实现双精度**。在

考虑一个顶点矩阵[100000][3]和一个类似C的函数:

double dist(double **vertex)

要从C调用此函数,需要创建以下指针矩阵:

^{pr2}$

如果我使用ctypes从python调用这个dist函数,则需要执行以下操作:

import numpy as np
import ctypes
vertex_np=np.reshape(np.random.randn(nb_millions*3e6),(nb_millions*1e6,3))
pt=ctypes.POINTER(ct.c_double)
vertex_pt= (pt*len(vertex_np))(*[row.ctypes.data_as(pt) for row in vertex_np])
result=lib.dist(ctypes.pointer(vertex_pt))

问题是创建顶点的循环。。。在

如何使用ndpointer从数字.ctypeslib? [如何使用numpy.ctypeslib.ndpointer?]在

谢谢你的帮助

-巴科

编辑-错误/低解决方案:

我发现避免此循环的唯一方法是使用以下命令修改dist声明:

double dist(double (*vertex)[3])

然后我可以在python代码中使用ndpointer:

lib.dist.argtypes = [np.ctypeslib.ndpointer(ndim=2,shape=(100000,3))]
result=lib.dist(vertex_np)

Tags: 函数importnumpyptlibdistasnp