在通过SWIG翻译方法时,我能推断出一些C ++参数吗?

时间:2013-11-27 06:01:05

标签: swig

(我正在重新提问使用一个例子,所以我想要的更清楚。)

说我有一个C ++函数:

void foobar(int arg0, int arg1);

我希望SWIG将其翻译成Python。但是,在Python中,我只想使用参数arg1,并且计算arg0是相同的。换句话说,我想让它成为Python

>>>foobar(x)

相当于C ++

foobar(x, x);

表示任何整数x。怎么样?

亚历克斯的答案指向了某个方向,但还远远不够。具体地

%typemap(in, numinputs=0) int arg0 {
}

非常有用,因为它允许我传递1个参数,而Python不会抱怨。好。但是,剩下的部分是,如何在类型地图中从arg0计算arg1

2 个答案:

答案 0 :(得分:1)

您可以使用inargout类型地图类型。它们的主要目的是允许在其他参数中返回多个值。但副作用是你用目标语言隐藏这些参数:

%typemap(in, numinputs=0, noblock=1) type1 *arg1 {
  type1 arg1;
  $1 = &arg1;
}

%typemap(argout) type1 *arg1 {
  // now *$1 has the value of Py_calculate_value_of_arg1()
  // you can do additional checks here
}

returnType foobar(type0 arg0, type1 *arg1) {
    *arg1 = Py_calculate_value_of_arg1();
}

python代码将是

foobar(arg0_value)

查看文档http://www.swig.org/Doc2.0/Python.html#Python_nn61

答案 1 :(得分:1)

使用multi-argument typemap。请注意,typemap将匹配其参数列表中具有参数集的任何函数。这通常用于将Python字符串映射到C中的一对参数,例如char*, size_t,但只要将单个Python参数映射到多个参数,就可以使用它:

%module x

// for a single input parameter in Python, if a function takes two integers
// named explicitly "int arg0, int arg1", map the two parameters to that
// same input.
%typemap(in) (int arg0, int arg1) %{
    $1 = PyInt_AsLong($input);
    $2 = $1;
%}

%inline %{
#include <stdio.h>
void foo(int arg0, int arg1)
{
    printf("%d %d\n",arg0,arg1);
}
void bar(int arg0, int arg1, int other)
{
    printf("%d %d %d\n",arg0,arg1,other);
}
void baz(int other, int arg0, int arg1)
{
    printf("%d %d %d\n",other,arg0,arg1);
}
%}

输出:

>>> import x
>>> x.foo(5)
5 5
>>> x.bar(1,5)
1 1 5
>>> x.baz(5,1)
5 1 1
相关问题