SWIG:使用std::map访问器和共享的\u ptr?

2024-04-18 05:56:26 发布

您现在位置:Python中文网/ 问答频道 /正文

<>我遇到了一个奇怪的问题,它使用了一个生成的Python包装器到C++类,当它被包装为^ {CD2>}类型时,我似乎不能使用^ {CD1>}的标准访问器函数。我设法制作了一个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

^{pr2}$

最后,我用来测试接口的测试脚本:

测试_接口.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和{}的类型时,它们都是各自类的{}引用:

<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)声明并重新编译,则映射访问器(在测试中_接口.py)工作愉快。当我检查myTestMap的类型时,它是:

<TestMap.testMap; proxy of <Swig Object of type 'testMap *' at 0x7f8eceb50630> >

所以,有两个问题:

  1. 为什么当我有SWIG对象指针引用(testMap*)时,我的访问器调用能正常工作,而当我有一个shared_ptr引用(例如,std::shared_ptr< testMap > *)时,访问器调用就不能正常工作了?在
  2. 如果我需要一个shared_ptr作为派生映射类型,我该如何解决这个问题?在

额外的问题:如果我声明testMap类型的shared_ptr的存在,SWIG为什么会自动将testMap*转换为std::shared_ptr<testMap>类型(即使它没有被初始化成这样?)在


Tags: ofpy类型maptypeswigintshared
1条回答
网友
1楼 · 发布于 2024-04-18 05:56:26

第一次myTestMap = tm.testMap()创建一个透明的共享\ptr。因此myTestMap[1]是共享的ptr的透明取消引用,随后将值分配给键。
第二次myTestMap = tm.testMap()创建空的std::map,因此myTestMap[1]是给映射的key=1赋值的。在

%shared_ptr(testMap)在语义上与%template(testMap) shared_ptr<testMap>相似。%template(testMapPtr) shared_ptr<testMap>将创建一个新的共享的ptr类型testMapPtr,该类型最初为NULL(参见{a1}),因此{}将取消对空值的引用,从而产生某些异常。
更新:%shared_ptr(testMap)创建一个完全透明的共享ptr,该ptr使用testMap默认构造函数初始化。在

相关问题 更多 >