SWIG:包装 std::map<key 时编译器错误,val *>

SWIG: Compiler error when wrapping std::map<key, val *>

本文关键字:错误 val gt 编译器 包装 map lt SWIG key std      更新时间:2023-10-16

我发现了这个老问题,对于值是指针而不是键的地图,我也有类似的问题。我收到此编译器错误:

error: no member named 'type_name' in 'swig::traits<C>'

当我编写自己的类型图或使用SWIG"std_map.i"类型映射时,都会发生这种情况。我需要采取哪些额外步骤才能为指向类型提供type_name?


最小工作示例:

%module stdmap;
%include "std_map.i"
%{
    class C
    {
        public:
             C() {};
    };
%}
class C
{
    public:
        C();
};
%template(mymap) std::map<int, C*>;

SWIG 可能对类指针感到困惑,因为它的包装器无论如何都使用指针。 无论如何,SWIG文档说(粗体我的(:

本节中的库模块提供对标准C++库部分(包括 STL(的访问。SWIG对STL的支持是一项持续的努力。对某些语言模块的支持非常全面,但一些较少使用的模块没有编写那么多的库代码。

如果您可以自由更改实现,我看到两种解决方法有效。 我使用Python作为测试的目标语言:

  1. 使用std::map<int,C>

%module stdmap
%include "std_map.i"
%inline %{
#include <memory>
class C
{
public:
    C() {};
};
%}
%template(mymap) std::map<int, C>;

输出(注意c无论如何都是 C* 的代理对象(:

>>> import stdmap
>>> c = stdmap.C()
>>> m = stdmap.mymap()
>>> m[1] = c
>>> c
<stdmap.C; proxy of <Swig Object of type 'C *' at 0x00000263B8DA5780> >
  1. 使用std::map<int, std::shared_ptr<C>>

%module stdmap
%include "std_map.i"
%include "std_shared_ptr.i"
%shared_ptr(C)
%inline %{
#include <memory>
class C
{
public:
    C() {};
};
%}
%template(mymap) std::map<int, std::shared_ptr<C> >;

输出(c现在是shared_ptr代理(:

>>> import stdmap
>>> c = stdmap.C()
>>> m = stdmap.mymap()
>>> m[1] = c
>>> c
<stdmap.C; proxy of <Swig Object of type 'std::shared_ptr< C > *' at 0x00000209C44D5060> >