【发布时间】:2017-07-31 15:47:54
【问题描述】:
我在使用 SWIG 生成的 Python 包装器到 C++ 类时遇到了一个奇怪的问题,当它被包装为 std::shared_ptr 类型时,我似乎无法使用 std::map 的标准访问器函数。我设法制作了一个 MWE,它重现了我观察到的奇怪行为。
TestMap.h
#include <iostream>
#include <map>
#include <memory>
class fooType{
public:
fooType() { };
~fooType() { };
void printFoo() { std::cerr << "FOO!" << std::endl; }
static std::shared_ptr<fooType> make_shared() {
return std::shared_ptr<fooType>(new fooType());
}
};
class testMap : public std::map<int, std::shared_ptr<fooType> > {
public:
void printBar() { std::cerr << "bar." << std::endl; }
};
然后是我的 SWIG 接口文件:
TestMap.i
%module TestMap
%include <std_map.i>
%include <std_shared_ptr.i>
%{
#include "TestMap.h"
%}
%shared_ptr(fooType);
%shared_ptr(testMap);
%shared_ptr(std::map<int, std::shared_ptr<fooType> > );
%template(fooMap) std::map< int, std::shared_ptr<fooType> >;
%include "TestMap.h"
最后是我用来测试界面的测试脚本:
test_interface.py
import TestMap as tm
ft = tm.fooType.make_shared()
myTestMap = tm.testMap()
myTestMap[1] = ft
正如所写,当我尝试使用地图访问器时出现以下错误:
Traceback (most recent call last):
File "test_interface.py", line 9, in <module>
myTestMap[1] = ft
File "/home/sskutnik/tstSWIG/TestMap.py", line 217, in __setitem__
return _TestMap.fooMap___setitem__(self, *args)
NotImplementedError: Wrong number or type of arguments for overloaded function 'fooMap___setitem__'.
Possible C/C++ prototypes are:
std::map< int,std::shared_ptr< fooType > >::__setitem__(std::map< int,std::shared_ptr< fooType > >::key_type const &)
std::map< int,std::shared_ptr< fooType > >::__setitem__(std::map< int,std::shared_ptr< fooType > >::key_type const &,std::map< int,std::shared_ptr< fooType > >::mapped_type const &
当我检查ft 和myTestMap 的类型时,它们都是各自类的std::shared_ptr 引用:
<TestMap.fooType; proxy of <Swig Object of type 'std::shared_ptr< fooType > *' at 0x7fa812e80a80> >
<TestMap.testMap; proxy of <Swig Object of type 'std::shared_ptr< testMap > *' at 0x7fa812e80c90> >
现在是奇怪的部分 - 如果我从 SWIG 接口文件中省略 %shared_ptr(TestMap) 声明并重新编译,地图访问器(在 test_interface.py 中)可以正常工作。当我检查myTestMap的类型时,它是:
<TestMap.testMap; proxy of <Swig Object of type 'testMap *' at 0x7f8eceb50630> >
那么,两个问题:
- 为什么当我有一个 SWIG 对象指针引用 (
testMap*) 时,我的访问器调用可以正常工作,但当我有一个shared_ptr引用(例如,std::shared_ptr< testMap > *)时却不能? - 鉴于我的派生地图类型需要
shared_ptr,我该如何解决?
额外问题:如果我声明 shared_ptr 类型存在 testMap 类型(即使它没有初始化),为什么 SWIG 会自动将 testMap* 转换为 std::shared_ptr<testMap> 类型这样吗?)
【问题讨论】: