编辑:大家好!!在
我目前正试图从Python访问C++函数,当我试图将Python列表作为参数传递给函数时,我遇到了一个问题。在
这是我试图访问的C++函数定义(用于向PC/SC阅读器发送命令):
SRpdu *SendAPDU(unsigned int uiAPDU, //Command
unsigned int ucLE, //Data expected for response
unsigned int ucLC, //Size of data buffer
unsigned char * pucDataBuf = 0); //data buffer
我的目标是像下面的例子一样从python调用这个函数。目标是将列表[1,2,3]转换为无符号char*缓冲区:
^{pr2}$在SWIG文档http://www.swig.org/Doc2.0/Python.html#Python_nn57中的示例“33.9.1将Python列表转换为char**”中,我定义了以下类型映射来处理unsigned char *
,但不幸的是,似乎没有使用typemap。实际上,我只能在忽略最后一个参数或将其设置为None的情况下使用该函数。在
Python代码:
>>> SendAPDU(0x02000000, 2, 0)
[36864, [30, 240]] #This call is working
>>> SendAPDU(0x02000000, 2, 0, None)
[36864, [30, 240]] #Also working
然后,如果我尝试为命令的数据放置一个列表(在前面的示例中替换None),我会收到以下错误:
>>> SendAPDU(0x02000000, 2, 4, [1, 2, 3, 4]) # HERE IT'S NOT WORKING
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "EMReaderEx.py", line 196, in SendAPDU
def SendAPDU(self, *args): return _EMReaderEx.EMReaderEx_SendAPDU(self, *args)
NotImplementedError: Wrong number or type of arguments for overloaded function 'EMReaderEx_SendAPDU'.
Possible C/C++ prototypes are:
EMReaderEx::SendAPDU(unsigned int,unsigned int,unsigned int,unsigned char *)
EMReaderEx::SendAPDU(unsigned int,unsigned int,unsigned int)
EMReaderEx::SendAPDU(SApdu &)
我想我们在这里是为了防止“参数类型错误”,所以我猜类型映射没有被使用,因为我认为,但不确定,函数没有被调用是因为参数格式不匹配。所以,主要的问题是如何传递一个列表,并确保它被函数接受(从而被typemap捕获)?在
我想我错过了一些东西,因为我没有找到任何有效的解决方案,它应该相对经常使用。在
以下是SWIG.i文件中typemap代码的代码:
%typemap(in) unsigned char * {
// Check if is a list
unsigned char *ucBuf = NULL;
if (PyList_Check($input) && PyList_Size($input) > 0) {
int size = PyList_Size($input);
int i = 0;
ucBuf = (unsigned char *) malloc((size+1)*sizeof(unsigned char));
for (i = 0; i < size; i++) {
PyObject *o = PyList_GetItem($input,i);
if (PyLong_Check(o))
ucBuf[i] = (unsigned char) PyLong_AsLong(o);
else {
PyErr_SetString(PyExc_TypeError,"list must contain integers");
free(ucBuf);
return NULL;
}
}
}
$1 = &ucBuf[0];
}
%typemap(freearg) unsigned char * {
if($1 != NULL)
free( $1);
}
在简历中,如何做SWIG类型映射,调用C++函数:SRpdu * SendAPDU(unsigned int uiAPDU, unsigned int ucLE, unsigned int ucLC, unsigned char * pucDataBuf);
就像python中的:
SendAPDU(0x02000000, 2, 4, [1, 2, 3, 4])
欢迎任何帮助 提前谢谢
对不起,如果我的英语不好,那不是我的母语。在
你应该看看module arrays.
特别是,您希望调用
fromlist
。如果您只是因为认为应该这样做而使用列表而不是字符串来传递,那么有一个字符串函数可用,fromstring
。无论哪种方式,都可以简单地用格式说明符'B'
(注意大写)初始化数组。在用法示例:
相关问题 更多 >
编程相关推荐