【发布时间】:2020-04-27 19:00:17
【问题描述】:
我是 swig 的新手,我正在尝试将 c++ 映射转换为 Perl 中的哈希。
有一个使用 c++ 的 Perl 扩展需要返回一个多维数组或映射到 Perl。 我在 swig 接口文件中使用了模板,但结果为空。
swig接口文件:
%include "exception.i"
%exception {
try {
$action
} catch (const std::exception &e) {
SWIG_exception_fail(SWIG_RuntimeError, e.what());
}
}
%module new_tr
%{
/* Put headers and other declarations here */
#include "new_tr.h"
%}
%include <std_map.i>
%template(StringStringMap) std::map<int, std::map<std::string,std::string>>;
%include "new_tr.h"
cpp 文件
std::map<int, std::map<std::string,std::string>> Memberfunction::m;
std::map<int, std::map<std::string,std::string>> Memberfunction::getResult()
{
return m;
}
perl 文件
use strict;
use new_tr;
use Data::Dumper;
my $new=new new_tr::some();
print Dumper($new->getResult());
电流输出:
$VAR1 = bless( {}, 'new_tr::StringStringMap' );
期望输出:(多维散列)
$VAR1 = bless( 0 => {
'Brown' => 'Manager',
'Smith' => 'Salesman',
'Albert' => 'Salesman',
},
1 => {
'Penfold' => 'Designer',
'Evans' => 'Tea-person',
'Jurgens' => 'Manager',
}, 'new_tr::StringStringMap' );
【问题讨论】:
-
cpp文件中,Database是什么?Database::getResult不应该是new_tr::getResult吗?同样在cpp文件中,您返回m,但未定义m。 -
我认为您需要为地图创建一个输出
typemap,例如%typemap(out) std::map<int, std::map<std::string,std::string>> { ... } -
@HåkonHægland 感谢您的回复,数据库是类的成员函数,m 是地图。我已编辑问题,请立即查看
-
@HåkonHægland 感谢您的回复,我如何在 swig 中使用 typemap 将 3d 地图转换为散列。
-
您的预期输出显示了一个
<string, ...>映射,但您的代码定义了一个<int, ..>映射,这是错字吗?