使用SWIG的Perl中的STL映射

ale*_*kuk 32 perl swig

这与我在SWIG邮件列表上的问题重复.

我试图在我的SWIG绑定中使用stl容器.除了在Perl中进行stl映射处理外,一切都运行良好.在C++方面,我有

std::map<std::string, std::string> TryMap(const std::map<std::string, std::string> &map) {
  std::map<std::string, std::string> modified(map);
  modified["7"] = "!";
  return modified;
}
Run Code Online (Sandbox Code Playgroud)

SWIG配置看起来像这样

%module stl

%include "std_string.i"

%include "std_map.i"
%template(StringStringMap) std::map<std::string, std::string>;

%{
  #include "stl.h"
%}

%include "stl.h"
Run Code Online (Sandbox Code Playgroud)

在我的Python脚本中,我可以这样调用TryMap

print dict(stl.TryMap({'a': '4'}))
Run Code Online (Sandbox Code Playgroud)

并获得美丽的输出

{'a': '4', '7': '!'}
Run Code Online (Sandbox Code Playgroud)

但在Perl我打电话

print Dumper stl::TryMap({'a' => '4'});
Run Code Online (Sandbox Code Playgroud)

并得到一个错误

TypeError in method 'TryMap', argument 1 of type 'std::map< std::string,std::string > const &' at perl.pl line 7.
Run Code Online (Sandbox Code Playgroud)

我实际上可以做类似的事情

my $map = stl::TryMap(stl::StringStringMap->new());
print $map->get('7');
Run Code Online (Sandbox Code Playgroud)

并得到'!',但这不是一个选项,因为有很多遗留代码使用"TryMap",期望普通的Perl哈希作为其输出.

我相信有一种方法可以解决这个问题,因为如果我使用stl向量和字符串而不是map,SWIG可以很好地解决Python中的这个特殊问题,即使在Perl中也是如此.

有没有办法在SWIG中使用Perl处理stl映射?我正在使用最新的SWIG 2.0.7

更新可能有问题perl5/std_map.i.太短了=)

$ wc -l perl5/std_map.i python/std_map.i 
   74 perl5/std_map.i
  305 python/std_map.i
Run Code Online (Sandbox Code Playgroud)

Fle*_*exo 2

我将你的 C++ 函数作为内联函数放入头文件中进行测试。

然后我能够构建一个 SWIG 接口来完成您正在寻找的任务。它有两个关键部分。首先,我编写了一个类型映射,允许将std::map或perl 散列作为输入提供给需要. 对于后者,它从 perl 哈希构建一个临时映射以用作参数。(这很方便,但可能很慢)。类型映射通过检查实际传入的内容来选择正确的行为。std::map

解决方案的第二部分是将一些 C++ 映射的成员函数映射到 perl 用于对哈希进行重载操作的特殊函数上。其中大多数都是简单地在%renameC++ 函数和 perl 函数兼容的情况下实现的,但是FIRSTKEY不能NEXTKEY很好地映射到 C++ 的迭代器上,因此这些是使用%extend和 (内部)另一个std::map来存储我们正在包装的映射的迭代状态来实现的。

这里没有实现用于返回映射的特殊类型映射,但是通过现在实现的特殊操作有额外的行为。

SWIG 界面如下所示:

%module stl

%include <std_string.i>
%include <exception.i>

%rename(FETCH) std::map<std::string, std::string>::get;
%rename(STORE) std::map<std::string, std::string>::set;
%rename(EXISTS) std::map<std::string, std::string>::has_key;
%rename(DELETE) std::map<std::string, std::string>::del;
%rename(SCALAR) std::map<std::string, std::string>::size;
%rename(CLEAR) std::map<std::string, std::string>::clear;

%{
#include <map>
#include <string>
// For iteration support, will leak if iteration stops before the end ever.
static std::map<void*, std::map<std::string, std::string>::const_iterator> iterstate;

const char *current(std::map<std::string, std::string>& map) {
  std::map<void*, std::map<std::string, std::string>::const_iterator>::iterator it = iterstate.find(&map);
  if (it != iterstate.end() && map.end() == it->second) {
    // clean up entry in the global map
    iterstate.erase(it);
    it = iterstate.end();
  }
  if (it == iterstate.end())
    return NULL;
  else
    return it->second->first.c_str();
}
%}

%extend std::map<std::string, std::string> {
  std::map<std::string, std::string> *TIEHASH() {
    return $self;
  }
  const char *FIRSTKEY() {
    iterstate[$self] = $self->begin();
    return current(*$self);
  }
  const char *NEXTKEY(const std::string&) {
    ++iterstate[$self];
    return current(*$self);
  }
}

%include <std_map.i>

%typemap(in,noblock=1) const std::map<std::string, std::string>& (void *argp=0, int res=0, $1_ltype tempmap=0) {
  res = SWIG_ConvertPtr($input, &argp, $descriptor, %convertptr_flags);
  if (!SWIG_IsOK(res)) {
    if (SvROK($input) && SvTYPE(SvRV($input)) == SVt_PVHV) {
      fprintf(stderr, "Convert HV to map\n");
      tempmap = new $1_basetype;
      HV *hv = (HV*)SvRV($input);
      HE *hentry;
      hv_iterinit(hv);
      while ((hentry = hv_iternext(hv))) {
        std::string *val=0;
        // TODO: handle errors here
        SWIG_AsPtr_std_string SWIG_PERL_CALL_ARGS_2(HeVAL(hentry), &val);
        fprintf(stderr, "%s => %s\n", HeKEY(hentry), val->c_str());
        (*tempmap)[HeKEY(hentry)] = *val;
        delete val;
      }
      argp = tempmap;
    }
    else {
      %argument_fail(res, "$type", $symname, $argnum); 
    }
  }
  if (!argp) { %argument_nullref("$type", $symname, $argnum); }
  $1 = %reinterpret_cast(argp, $ltype);
}

%typemap(freearg,noblock=1) const std::map<std::string, std::string>& {
  delete tempmap$argnum;
}

%template(StringStringMap) std::map<std::string, std::string>;

%{
#include "stl.h"
%}

%include "stl.h"
Run Code Online (Sandbox Code Playgroud)

然后我调整了你的示例 perl 来测试:

use Data::Dumper;
use stl;

my $v = stl::TryMap(stl::StringStringMap->new());
$v->{'a'} = '1';
print Dumper $v;
print Dumper stl::TryMap({'a' => '4'});
print Dumper stl::TryMap($v);


foreach my $key (keys %{$v}) {
  print "$key => $v->{$key}\n";
}

print $v->{'7'}."\n";
Run Code Online (Sandbox Code Playgroud)

我能够成功运行:

Got map: 0x22bfb80
$VAR1 = bless( {
                 '7' => '!',
                 'a' => '1'
               }, 'stl::StringStringMap' );
Convert HV to map
a => 4
Got map: 0x22af710
In C++ map: a => 4
$VAR1 = bless( {
                 '7' => '!',
                 'a' => '4'
               }, 'stl::StringStringMap' );
Got map: 0x22bfb20
In C++ map: 7 => !
In C++ map: a => 1
$VAR1 = bless( {
                 '7' => '!',
                 'a' => '1'
               }, 'stl::StringStringMap' );
7 => !
a => 1
!
Run Code Online (Sandbox Code Playgroud)

您还可以将此对象绑定到哈希,例如:

use stl;

my $v = stl::TryMap(stl::StringStringMap->new());
print "$v\n";

tie %foo, "stl::StringStringMap", $v;

print $foo{'a'}."\n";
print tied(%foo)."\n";
Run Code Online (Sandbox Code Playgroud)

理论上,您可以编写一个输出类型映射来在每次函数调用返回时自动设置此绑定,但到目前为止,我还没有成功编写一个同时适用于绑定和 SWIG 运行时类型系统的类型映射。

应该注意的是,这不是生产就绪的代码。据我所知,内部映射存在线程安全问题,并且还缺少一些错误处理。除了您在上面看到的内容之外,我还没有完全测试 Perl 端的所有哈希操作工作。通过与宏交互使其更通用也很好swig_map_common。最后,我无论如何都不是 Perl 大师,而且我也没有太多使用 C API,因此在该领域需要谨慎一些。