2009-08-08 80 views
1

我正在尝试编写一个将多个/变量参数转换为一个输入参数的类型映射。如何将多个参数合并到一个SWIG参数

例如,假设我有一个函数需要一个向量。

void foo(vector<int> x); 

而且我想这样称呼它(恰好是在Perl)

foo(1,2,3,4); 

类型映射应该采取的参数($ argnum,...),他们收集到一个载体,然后把它传给foo。

我有这个至今:

typedef vector<int> vectori; 
%typemap(in) (vectori) { 
    for (int i=$argnum-1; i<items; i++) { 
     $1->push_back(<argv i>); // This is language dependent, of course. 
    } 
} 

这会工作,只是SWIG检查参数的个数

if ((items < 1) || (items > 1)) { 
    SWIG_croak("Usage: foo(vectori);"); 
} 

如果我做的:

void foo(vectori, ...); 

痛饮将期待用两个参数调用foo。

foo(arg1, arg2); 

也许有一种方法来告诉夜风从呼叫ARG2抑制对foo?因为我想有不同的typemaps,取决于foo是期待类型(int,字符串数组,等等)

void foo(...) 

我不能在我的。我用这个。也许有办法给一个类型“...”

有没有办法做到这一点?

回答

0

SWIG确定SWIG生成绑定时的参数计数。 SWIG确实为可变参数列表提供了一些有限的支持,但我不确定这是正确的方法。如果您有兴趣,可以在SWIG vararg文档部分阅读更多关于它的信息。

我认为一个更好的方法是将这些值作为数组引用传递。然后你会类型表看起来像这样(未测试):

%typemap(in) vectori (vector<int> tmp) 
{ 
    if (!SvROK($input)) 
     croak("Argument $argnum is not a reference."); 

    if (SvTYPE(SvRV($input)) != SVt_PVAV) 
     croak("Argument $argnum is not an array."); 

    $1 = &$tmp; 

    AV *arrayValue = (AV*)SvRV($input); 
    int arrayLen = av_len(arrayLen); 

    for (int i=0; i<=arrayLen; ++i) 
    { 
     SV* scalarValue = av_fetch(arrayValue , i, 0); 
     $1->push_back(SvPV(*scalarValue, PL_na)); 
    } 
}; 

然后从Perl中你会使用数组表示法:

@myarray = (1, 2, 3, 4); 
foo(\@myarray); 
1

痛饮内置了一些STL类的支持。试试这个你痛饮.i文件:

%module mymod 

%{ 
#include <vector> 
#include <string> 
void foo_int(std::vector<int> i); 
void foo_str(std::vector<std::string> i); 
%} 

%include <std_vector.i> 
%include <std_string.i> 
// Declare each template used so SWIG exports an interface. 
%template(vector_int) std::vector<int>; 
%template(vector_str) std::vector<std::string>; 

void foo_int(std::vector<int> i); 
void foo_str(std::vector<std::string> i); 

然后在所选择的语言与数组语法调用它:

#Python 
import mymod 
mymod.foo_int([1,2,3,4]) 
mymod.foo_str(['abc','def','ghi']) 
相关问题