swig为何将python列表无缝转换为std :: vector而不是std :: set?

问题描述 投票:0回答:1

我使用swig进行了一些试验,以将基本的C ++类扩展到python。我发现了一个行为与到目前为止我无法解释的集合的使用有关。这是我的脚本:

MyClass.h:

#pragma once
#include <set>
#include <vector>

class MyClass
{
public:
    MyClass();
    void setSTLVector(const std::vector<int> &vector);
    void setSTLSet(const std::set<int> &set);

private:
    std::vector<int> _stlVector;
    std::set<int> _stlSet;
};

MyClass.cpp:

#include "MyClass.h"

MyClass::MyClass()
{
}

void MyClass::setSTLVector(const std::vector<int> &vector)
{
    _stlVector = vector;
}

void MyClass::setSTLSet(const std::set<int> &set)
{
    _stlSet = set;
}

MyClass.i:

%module MyClass

%{
    #include "MyClass.h"
%}

%include <typemaps.i>

%include "std_vector.i"
%template(IntVector) std::vector<int>;

%include "std_set.i"
%template(IntSet) std::set<int>;

%include "MyClass.h"

编译所有内容时(似乎)可以。当我将扩展程序运行到python中时,我的误解开始了。确实:

In [1]: import MyClass
In [2]: cls = MyClass.MyClass()
In [3]: cls.setSTLVector([1,2,3,4])

至少可以很好地完成我的预期,即python list of integers在内部std::vector<int> casted。对于集合:

In [1]: import MyClass
In [2]: cls = MyClass.MyClass()
In [3]: cls.setSTLVector({1,2,3,4})

触发以下错误:

TypeError: in method 'MyClass_setSTLSet', argument 2 of type 'std::set< int,std::less< int >,std::allocator< int > > const &'

此错误可能与我使用swig中定义的类型声明集合时遇到的另一个错误有关:

In [1]: import MyClass
In [2]: cls = MyClass.IntSet({1,2,3,4})

给出:

NotImplementedError: Wrong number or type of arguments for overloaded function 'new_IntSet'.
  Possible C/C++ prototypes are:
    std::set< int >::set(std::less< int > const &)
    std::set< int >::set()
    std::set< int >::set(std::set< int > const &)

您对我做错了还是正常行为有任何想法吗?

swig
1个回答
1
投票

直觉上std_set.i的类型映射期望Python list作为输入而不是set

>>> import MyClass
>>> cls = MyClass.MyClass()
>>> cls.setSTLVector([1,2,3,4]) # works
>>> cls.setSTLSet([1,2,3,4])    # works
>>> cls.setSTLSet({1,2,3,4})    # doesn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\MyClass.py", line 385, in setSTLSet
    return _MyClass.MyClass_setSTLSet(self, set)
TypeError: in method 'MyClass_setSTLSet', argument 2 of type 'std::set< int,std::less< int >,std::allocator< int > > const &'**strong text**

您必须定义自己的自定义类型映射以将set作为输入。

© www.soinside.com 2019 - 2024. All rights reserved.