我试图通过使用SWIG进行包装来从python访问C ++函数。该函数使用两个数组作为长度cL
的输入,另一个作为较小长度的输出。 SWIG .i文件是:
%module polcvx
%include "typemaps.i"
%apply int *INPUT {int *cL};
%typemap(in) float r[cL] (float temp[cL]) {
int i;
if (!PySequence_Check($input)) {
PyErr_SetString(PyExc_ValueError, "Expected a sequence");
SWIG_fail;
}
if (PySequence_Length($input) != cL) {
PyErr_SetString(PyExc_ValueError, "Size mismatch. Expected more or less elements than 4th argument");
SWIG_fail;
}
for (i = 0; i < cL; i++) {
PyObject *o = PySequence_GetItem($input, i);
}
$1 = temp;
}
%typemap(in) float t[cL] (float temp1[cL]) {
int i;
if (!PySequence_Check($input)) {
PyErr_SetString(PyExc_ValueError, "Expected a sequence");
SWIG_fail;
}
if (PySequence_Length($input) != cL) {
PyErr_SetString(PyExc_ValueError, "Size mismatch. Expected more or less elements than 4th argument");
SWIG_fail;
}
for (i = 0; i < cL; i++) {
PyObject *o = PySequence_GetItem($input, i);
}
$2 = temp1;
}
%typemap(in, numinputs=0) int *hull[ANY] (int temp2[ANY]) {
$3 = &temp2;
}
%typemap(argout) int *hull[ANY] {
int i;
$result = PyList_New($3_dim0);
for (i = 0; i < $3_dim0; i++) {
PyObject *o = PyFloat_FromDouble((double) $3[i]);
PyList_SetItem($result, i, o);
}
}
%{
#define SWIG_FILE_WITH_INIT
#include "cvxp.hpp"
%}
int cvx( int hull[],float r[], float t[], int cL);
并在python中实现为
import _polcvx
rad=[10,5,2,20,15,7,10,45,12]
theta=[0.5236 , 0.7854 , 1.5708 , 2.6180 , 2.9671 , 3.3161 , 4.0143 , 4.7124 , 6.1087]
l=len(rad)
ls=[]
i=_polcvx.cvx(5,rad2,theta,l)
我在python中遇到错误
Traceback (most recent call last):
File "E:\Hull\cpp and py conversion\CvxPolar.py", line 65, in <module>
i=_polcvx.cvx(ls,rad2,theta,l)
TypeError: in method 'cvx', argument 1 of type 'int []'
由于函数使用指针访问数组变量,因此无法确定要在.i文件中完成的正确配置。