如何将多个参数合并为一个 SWIG 参数 [英] How can I collapse multiple arguments into one SWIG parameter
问题描述
我正在尝试编写一个将多个/可变参数转换为一个输入参数的类型映射.
I'm trying to write a typemap that converts multiple/variable arguments into one input parameter.
例如,假设我有一个接受向量的函数.
For example, say I have a function that takes a vector.
void foo(vector<int> x);
我想这样称呼它(碰巧是在 Perl 中)
And I want to call it like this (happens to be in Perl)
foo(1,2,3,4);
typemap 应该接受参数 ($argnum, ...),将它们收集到一个向量中,然后将其传递给 foo.
The typemap should take arguments ($argnum, ...), gather them into one vector and then pass that to 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 检查参数的数量
This would work, except that SWIG checks the number of arguments
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: foo(vectori);");
}
如果我这样做:
void foo(vectori, ...);
SWIG 将期望使用两个参数调用 foo.
SWIG will expect to call foo with two arguments.
foo(arg1, arg2);
也许有一种方法可以告诉 SWIG 从对 foo 的调用中抑制 arg2?
Perhaps there's a way to tell SWIG to suppress arg2 from the call to foo?
我不能在我的 .i 中使用它:
I can't use this in my .i:
void foo(...)
因为我想要不同的类型映射,这取决于 foo 期望的类型(int 数组、字符串数组等等).也许有一种方法可以为..."提供类型
because I want to have different typemaps, depending on the types that foo is expecting (an array of int, strings, whatever). Maybe there's a way to give a type to "..."
有没有办法做到这一点?
Is there a way to do this?
推荐答案
SWIG 内置了对某些 STL 类的支持.为您的 SWIG .i 文件试试这个:
SWIG has built-in support for some STL classes. Try this for your SWIG .i file:
%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);
然后使用所选语言的数组语法调用它:
Then call it with array syntax in the language of choice:
#Python
import mymod
mymod.foo_int([1,2,3,4])
mymod.foo_str(['abc','def','ghi'])
这篇关于如何将多个参数合并为一个 SWIG 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!