【问题标题】:How to make interface for std::pair<> with no default constructor in swig & python?如何在 swig & python 中为没有默认构造函数的 std::pair<> 创建接口?
【发布时间】:2017-03-30 09:10:58
【问题描述】:

我将使用 swig 制作 python 包装器。 我在 c++ dll 中有一些类和类型。

class Image
{
public:
    Image(const Image&);
    Image& operator= (const Image&);
    ~Image();

    unsigned int width() const;
    unsigned int height() const;
};
struct Property
{
    std::string path;
    std::string datetime;
};
typedef std::pair<Image, Property> MyImage;
class Manage
{
public:
    Manage();
    ~Manage();
    void addMyImage(MyImage img);
    MyImage getMyImage(int index);
};

我在这个之后制作了 swig 接口文件:

%include "std_pair.i"
%template(MyImage) std::pair<Image, Property>;
class Image
{
public:
    Image(const Image&);
    ~Image();

    unsigned int width() const;
    unsigned int height() const;
};
class Manage
{
public:
    Manage();
    ~Manage();

    void addMyImage(std::pair<Image, Property> img);
    std::pair<Image, Property> getMyImage(int index);
};

我运行命令swig -c++ -python Test.swig

我在 Visual Studio 中编译 Test_wrapper.cxx,出现以下错误:

error C2512: 'Image' : 没有合适的默认构造函数可用

所以我尝试使用swig -c++ -python -nodefaultctor Test.swig。 但它是一样的。

============更新============

问题是std::pair&lt;Image, Property&gt;。对创建时,它调用参数的构造函数。图像没有默认构造函数。所以会发生错误。

我该如何解决? 谢谢。

【问题讨论】:

  • 我被难住了。我理解为什么我认为 nodefaultctor 不起作用(有一个明确的,所以它不是默认的)。我找不到任何可行的解决方法。 stackoverflow.com/questions/13569939/… 看起来也很相关。当您显示的代码足以复制和粘贴时,值得提出的问题更容易回答 - 我必须在 C++ 标头中添加 #include &lt;utility&gt; 并在 SWIG 界面中添加 %module %{ #include "test.hh" %} 以使它们尽可能远你的错误。

标签: python c++ swig


【解决方案1】:

我终于找到了一种方法来完成这项工作。首先,由于您有 addMyImagegetMyImage 的按值传递语义,您需要使用 %feature("valuewrapper") 在生成的代码中打开按值传递包装转换,否则您将获得默认构造的对在生成的代码中。

其次,您需要防止 SWIG 公开不带参数的 std::pair 构造函数。 (我认为这与%nodefaultctor 指令不同,因为这样的构造函数是显式编写的,而不是简单地假定存在)。我花了很长时间才意识到最简单(?)方法的正确语法,我相信这是使用高级重命名。

所以你需要在%include &lt;std_pair.i&gt; 指令之前添加两行:

%feature("valuewrapper") std::pair<Image,Property>;
%rename("$ignore",$isconstructor,fullname=1) "std::pair<(Image,Property)>";
%include "std_pair.i"

然而,这确实禁用了std::pair&lt;Image,Property&gt; 中的所有构造函数。

【讨论】:

  • 谢谢。太好了。错误 C2512 已修复。但我不能使用 MyImage。我认为它忽略了 MyImage 的所有构造函数。我需要一个构造函数来使用 Image 和 Property 初始化 MyImage。我只需要忽略默认构造函数。我该怎么做?
猜你喜欢
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 2018-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多