问题描述
我正在尝试从使用 SWIG for Python 包装的 C 函数输出一组值.我试图做的方式是使用以下类型映射.
I am trying to output an array of values from a C function wrapped using SWIG for Python. The way I am trying to do is using the following typemap.
伪代码:
int oldmain() {
float *output = {0,1};
return output;
}
字体映射:
%typemap(out) float* {
int i;
$result = PyList_New($1_dim0);
for (i = 0; i < $1_dim0; i++) {
PyObject *o = PyFloat_FromDouble((double) $1[i]);
PyList_SetItem($result,i,o);
}
}
我的代码编译得很好,但是当我运行访问这个函数时它挂起(没有更多的方法来调试它).
My code compiles well, but it hangs when I run access this function (with no more ways to debug it).
对我哪里出错有什么建议吗?
Any suggestions on where I am going wrong?
谢谢.
推荐答案
这应该可以帮助您:
/* example.c */
float * oldmain() {
static float output[] = {0.,1.};
return output;
}
您在这里返回一个指针,而 swig 不知道它的大小.普通的 $1_dim0 不起作用,所以你必须硬编码或做一些其他的魔术.像这样:
You are returning a pointer here, and swig has no idea about the size of it. Plain $1_dim0 would not work, so you would have to hard code or do some other magic. Something like this:
/* example.i */
%module example
%{
/* Put header files here or function declarations like below */
extern float * oldmain();
%}
%typemap(out) float* oldmain {
int i;
//$1, $1_dim0, $1_dim1
$result = PyList_New(2);
for (i = 0; i < 2; i++) {
PyObject *o = PyFloat_FromDouble((double) $1[i]);
PyList_SetItem($result,i,o);
}
}
%include "example.c"
那么在python中你应该得到:
Then in python you should get:
>> import example
>> example.oldmain()
[0.0, 1.0]
添加类型映射时,您可能会发现 -debug-tmsearch
非常方便,即
When adding typemaps you may find -debug-tmsearch
very handy, i.e.
swig -python -debug-tmsearch example.i
在为 float *oldmain
寻找合适的out"类型映射时,应该清楚地表明使用了您的类型映射.此外,如果您只是想访问 c 全局变量数组,您可以使用 varout
的类型映射而不是 out
来执行相同的技巧.
Should clearly indicate that your typemap is used when looking for a suitable 'out' typemap for float *oldmain
. Also if you just like to access c global variable array you can do the same trick using typemap for varout
instead of just out
.
这篇关于Python/SWIG:输出一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!