SWIG C到Python的int数组 [英] SWIG C-to-Python Int Array
问题描述
我试图从Python的使用痛饮用以下原型访问C函数:
I am trying to access a C function with the following prototype from python using swig:
int cosetCoding(int writtenDataIn, int newData, const int memoryCells, int *cellFailure, int failedCell);
痛饮创建没有问题中的.so,我可以将其导入到蟒蛇,但是当我尝试用下面的访问它:
Swig creates the .so with no problems and I can import it into python, but when I try to access it with the following:
cosetCoding.cosetCoding(10,11,8,[0,0,0,0,0,0,0,0],0)
我得到以下回溯:
I get the following traceback:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: in method 'cosetCoding', argument 4 of type 'int *'
指针应该是一个int数组的大小由memoryCells定义
The pointer is supposed to be an int array with size defined by memoryCells
推荐答案
如果你可以使用ctypes的。它更简单。不过,既然你问SWIG,你需要的是描述如何处理为int *类型映射一个。痛饮不知道有多少整数可能指向。下面是一个例子痛饮文档中砍死在<一个href=\"http://www.swig.org/Doc2.0/SWIGDocumentation.html#Typemaps_multi_argument_typemaps\">multi-argument typemaps :
Use ctypes if you can. It is simpler. However, since you asked for SWIG, what you need is a typemap describing how to handle the int*. SWIG doesn't know how many integers may be pointed to. Below is hacked from an example in the SWIG documentation on multi-argument typemaps:
%typemap(in) (const int memoryCells, int *cellFailure) {
int i;
if (!PyList_Check($input)) {
PyErr_SetString(PyExc_ValueError, "Expecting a list");
return NULL;
}
$1 = PyList_Size($input);
$2 = (int *) malloc(($1)*sizeof(int));
for (i = 0; i < $1; i++) {
PyObject *s = PyList_GetItem($input,i);
if (!PyInt_Check(s)) {
free($2);
PyErr_SetString(PyExc_ValueError, "List items must be integers");
return NULL;
}
$2[i] = PyInt_AsLong(s);
}
}
%typemap(freearg) (const int memoryCells, int *cellFailure) {
if ($2) free($2);
}
请注意,这个定义,从Python中调用时离开了 memoryCells
参数,只传递一个数组,如 [1,2,3 4]
为 cellFailure
。类型映射将生成 memoryCells
参数。
Note that with this definition, when called from Python leave out the memoryCells
parameter and just pass an array such as [1,2,3,4]
for cellFailure
. The typemap will generate the memoryCells
parameter.
P.S。我可以发布一个完全工作示例(适用于Windows),如果你想要它。
P.S. I can post a fully working example (for Windows) if you want it.
这篇关于SWIG C到Python的int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!