gpt4 book ai didi

c++ - ctypes:初始化数组数组并传递给 C 函数

转载 作者:行者123 更新时间:2023-11-30 04:10:12 27 4
gpt4 key购买 nike

我一直在玩 ctypes,遇到了两个问题:

问题 1. 我想使用 double* 数组构建一个 cellComplex,但我想要 new_cellComplex接受 double* 的数组(连同 size_t 参数)而不是固定数量的 double*。对于固定数字,代码看起来像这样(并且运行良好):

extern "C" {
void * new_cellComplex(double* p_x, double* p_y, double* p_z) {

std::vector< std::pair<double,double> > point;
point.push_back( std::make_pair(p_x[0],p_x[1]));
point.push_back( std::make_pair(p_x[0],p_x[1]));
point.push_back( std::make_pair(p_x[0],p_x[1]));

cellComplex<double>* cmplx = new cellComplex<double>(point);
return cmplx;
}

使用 Python 代码:

import ctypes

cellComplex_lib = ctypes.cdll.LoadLibrary('./cellComplex_lib.so')
cellComplex_lib.new_cellComplex.restype = ctypes.c_void_p
cellComplex_lib.new_cellComplex.argtypes = [ctypes.c_double*2,
ctypes.c_double*2,
ctypes.c_double*2]

p_x = (ctypes.c_double*2)(0.0,1.0)
p_y = (ctypes.c_double*2)(0.0,1.0)
p_z = (ctypes.c_double*2)(0.0,1.0)

cmplx = cellComplex_lib.new_cellComplex(p_x,p_y,p_z)

我宁愿有以下(哪些段错误):

extern "C" {
void * new_cellComplex(double** p, size_t dim) {

std::vector< std::pair<double,double> > point;
for (size_t i=0; i<dim; ++i) {
point.push_back( std::make_pair(p[i][0],p[i][1]));
}
cellComplex<double>* cmplx = new cellComplex<double>(point);
return cmplx;
}
}

使用 Python 代码:

import ctypes

dim = 3
cellComplex_lib = ctypes.cdll.LoadLibrary('./cellComplex_lib.so')
cellComplex_lib.new_cellComplex.restype = ctypes.c_void_p
cellComplex_lib.new_cellComplex.argtypes = [(ctypes.c_double*2)*dim,
ctypes.c_size_t]

p_x = (ctypes.c_double*2)(0.0,1.0)
p_y = (ctypes.c_double*2)(0.0,1.0)
p_z = (ctypes.c_double*2)(0.0,1.0)

p = ((ctypes.c_double*2)*dim)(p_x,p_y,p_z)

cmplx = cellComplex_lib.new_cellComplex(p,dim)

^这不起作用,我不知道为什么。

问题 2。(包含在这里是因为它在问题 1很明显)我从我的 C 返回一个基本上匿名的指针 代码!这感觉,好吧,很脏,必须有更好的方法来返回自定义数据类型并在 Python 中处理它。作为记录,我非常感谢this stackoverflow answer我在哪里学会了这样的魔法 - 但只要它在我的代码中,我就无法在晚上休眠...

最佳答案

代替 double **,使用 double [][2]。您正在传递一个连续的 C 数组,您希望将其作为指向一行 2 项的指针进行访问。第一个索引是行索引。

将数组声明为double **是一个指向double指针的指针,所以p[i]是一个指针,并且p[i][0] 再次取消引用它。但是 p[i] 根据您的数据偶然是一个 NULL 指针。

Refer to the comp.lang.c FAQ, question 6.18: My compiler complained when I passed a two-dimensional array to a function expecting a pointer to a pointer.

对于返回类型,您可以继承c_void_p,或根据section 15.17.1.7 的最后一段使用钩子(Hook)from_param_as_parameter_在 ctypes 文档中。

关于c++ - ctypes:初始化数组数组并传递给 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20752834/

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