c – 将python列表包装到unsigned char *
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c – 将python列表包装到unsigned char *,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2898字,纯文字阅读大概需要5分钟。
内容图文
![c – 将python列表包装到unsigned char *](/upload/InfoBanner/zyjiaocheng/769/89a1dd947a9246d48728cdecb0fd16cc.jpg)
编辑:大家好!
我正在尝试从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]转换为unsigned char *缓冲区:
SendAPDU(0x01020304, 0, 3, [1, 2, 3])
从SWIG文档http://www.swig.org/Doc2.0/Python.html#Python_nn57中的示例“33.9.1将Python列表转换为char **”开始,我定义了以下typemap来处理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);
}
在Resume中,如何使用SWIG typemap来调用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.
特别是,您希望从列表中致电.如果您正在使用列表而不是字符串而只是因为您认为这是您应该做的事情,那么可以使用字符串函数fromstring.无论哪种方式,您只需使用格式说明符’B’初始化数组(注意资本).
用法示例:
array ('B', [1, 2, 1, 0, 3, 6, 0, 6])
内容总结
以上是互联网集市为您收集整理的c – 将python列表包装到unsigned char *全部内容,希望文章能够帮你解决c – 将python列表包装到unsigned char *所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。