tags:

views:

387

answers:

1

In Perl, I'm accustomed to passing arrays to and from subs

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

How can I achieve similar behavior with SWIG'ed functions?

SWIG'ing this:

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;
}

Yields a sub that expects an array reference and returns an array reference? I'm using the stl templates that come with SWIG.

Do I need to write a typemap for this? Seems this would already be covered somewhere.

+1  A: 

The typemap is already coded for you, but you still have to instantiate it.

As pointed in the SWIG/STL doc, you have to declare the vector<int> as a vectori and convert your Perl array to it.

If you want to have a transparent convertion you have to code the typemap yourself.

Code examples below, with your example.

print_list.hxx

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

print_list.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;
}

print_list.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));
Steve Schnepp