ctypes: Initialize array of arrays and pass to C function
我一直在玩 ctypes,遇到了两个问题:
问题 1. 我想使用
1 2 3 4 5 6 7 8 9 10 11 | 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 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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) |
我宁愿有以下(段错误):
1 2 3 4 5 6 7 8 9 10 11 | 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 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 中很明显)我正在从我的
使用
将数组声明为
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.
对于返回类型,您可以继承