perl - 如何将 Perl 数组传递给 SWIG 或从 SWIG 传递出去?

标签 perl swig

在 Perl 中,我习惯于在 subs 之间传递数组

sub abc {
  foreach my $x (@_) { print $x; }
  return (0, 1, 2);
}

如何使用 SWIG 的函数实现类似的行为?

SWIG 这个:

std::vector<int> print_list(std::vector<int> l)
{
  std::vector<int>::iterator iter;
  for(iter=l.begin(); iter!=l.end(); iter++) {
    printf("int %d\n", *iter);
  }

  return l;
}

生成一个需要数组引用并返回数组引用的子程序?我正在使用 SWIG 附带的 STL 模板。

我需要为此编写类型映射吗?似乎这已经在某个地方被涵盖了。

最佳答案

类型映射已经为您编码,但您仍然需要实例化它。

正如 SWIG/STL doc 中指出的那样,您必须声明 vector<int>作为vectori并将 Perl 数组转换为它

如果您想要透明转换,您必须自己编写类型映射。

下面的代码示例以及您的示例

打印列表.hxx

#include <vector>
std::vector<int> print_list(std::vector<int> l);

打印列表.cpp

#include <cstdio>
#include <vector>

#include "print_list.hxx"

using namespace std;

vector<int> print_list(vector<int> l) {
    vector<int>::iterator iter;
    for(iter=l.begin(); iter!=l.end(); iter++) {
        printf("int %d\n", *iter);
    }
    return l;
}

打印列表.i

%module print_list
%include "std_string.i"
%include "std_vector.i"

namespace std {
    %template(vectori) vector<int>;
    %template(vectord) vector<double>;
};


%{
#include "print_list.hxx"
%}


%include "print_list.hxx"

test_print_list.pl

#! /usr/bin/perl
use Data::Dumper;

use print_list;

my @row = (1, 2, 4);
my $vi = new print_list::vectori();
foreach my $val (@row) {
    $vi->push($val);
}

print Dumper(print_list::print_list($vi));

关于perl - 如何将 Perl 数组传递给 SWIG 或从 SWIG 传递出去?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1208126/

相关文章:

perl - 使用 Perl,如何查找和删除具有特定后缀的文件?

java - 如何使用 swig 类型映射将 std::vector<std::pair<std::string, int>> 从 Java 返回到 C++

c++ - Swig、Python、C++ : TypeError: in method 'Geodatabase_Open' , 类型 'std::string' 的参数 2

shell - sed:打印模式 A 最后匹配的所有行,然后只打印匹配模式 B 的行

python - Moose 与 Python 的 OO 系统相比如何?

python - SWIG Python - 包装一个需要双指针指向结构的函数

python - SWIG:结构中的自定义类型和 python 中的赋值

c++ - 如何使用 SWIG 和 CGO 将 io.Reader 转换为 std::istream?

c++ - 在 C++ 和 Perl 之间使用的 YAML

mysql - 如何检查mySQL数据库中的值是否存在?