如何在python脚本中发送c api数组或结构 [英] How do I send a c api an array or struct in a python script
问题描述
我是python的新手,我似乎无法将数组或结构的参数从python脚本发送到c api。我已经发送了int和字符串确定。
我已经设法将python嵌入到调用python模块脚本的C中。我也在使用SWIG。我将使用python unitttest来测试对c api的调用。
我有一个很好的挖掘,所有简单的例子都将params显示为int或字符串。似乎没有发送数组或结构的示例。如何通过SWIG从python脚本将C数组或结构发送到c api?
是否有转换?我尝试发送simple_array = array('i',[8,9])它是否在swig文件中?任何帮助表示赞赏!
Hi,
I am new to python and I can't seem to send array's or struct's params from a python script to a c api. I have sent int's and strings ok.
I have managed to embed python into C that calls a python module script. I am also using SWIG. I will be using python unitttest to test calls to c api's.
I have had a good dig around and all the simple examples show params as int's or strings. There seems no examples of sending arrays or structs. How do I send from a python script a C array or struct to a c api via SWIG?
Is there a conversion? I tried sending "simple_array=array('i',[8,9])" Is it in the swig file? Any help appreciated!
/*simple_api.c*/
#include <stdio.h>
int Simple_api_Connector_UTF_SimplePointerArrayWriteTestFunc(int *pArray);
int Simple_api_Connector_UTF_SimplePointerArrayWriteTestFunc(int *pArray)
{
printf("Simple_api_Connector_UTF_SimpleArrayWriteTestFunc: array byte 1:%x array byte 2: %x\n", pArray[1], pArray[2]);
return 1;
}
-----------
-----------
/*simple_api.i*/
%module simple_api
int Simple_api_Connector_UTF_SimplePointerArrayWriteTestFunc(int *pArray);
-----------
-----------
#py_test_python.py
#!/usr/bin/env python
'''py_test_python.py - Python source designed to '''
'''demonstrate the use of python embedding in and out'''
def py_test_python_func():
simple_api.Simple_api_Connector_UTF_ArrayWriteTestFunc([1,2])#<- tried loads here but always an error!
推荐答案
swig中有辅助函数来处理数组和向量。它应该使事情更容易处理。
http://www.swig。 org / Doc1.3 / SWIG.html#SWIG_nn26 [ ^ ]
http://www.swig .org / Doc2.0 / SWIGDocumentation.html#Library_carrays [ ^ ]
There are helper functions in swig to handle arrays and vectors. It should make things easier to handle.
http://www.swig.org/Doc1.3/SWIG.html#SWIG_nn26[^]
http://www.swig.org/Doc2.0/SWIGDocumentation.html#Library_carrays[^]
谢谢。
我找到了一个工作类型图来转换数组变量在SWIG接口(.i)文件中,用于将一个int数组从python脚本写入c api:
Thanks.
I have found a working typemap to convert the array variable in the SWIG interface (.i) file that works for writing an int array from the python script to the c api:
//type map for an input int array, this will calculate the length
%typemap(in) (const int length_in, int *int_in_array)
{
int i;
if (!PyList_Check(
input))
{
PyErr_SetString(PyExc_ValueError, 期待列表);
return NULL;
}
input)) { PyErr_SetString(PyExc_ValueError, "Expecting a list"); return NULL; }
这篇关于如何在python脚本中发送c api数组或结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!