【问题标题】:std::set support in java swigjava swig 中的 std::set 支持
【发布时间】:2015-09-28 08:57:43
【问题描述】:

在我的 java 代码中,我想调用 std::set 默认构造函数和插入,例如以下 C++ 代码:

struct foo;
foo bar();
std::set<foo> toto;
toto.insert(b);

Swig provides support for various STL containers for javastd::vectorstd::stringstd::map... 但是不支持std::set

所以我发现了这个solution,它涉及一个 C++ 包装器和一个 java 包装器。我还没有尝试过,我不确定它是否会起作用,我觉得它不方便。

我们可以通过提出一个处理基本集合构造函数和插入的最小 swig 接口来做得更好吗?

例如一个接口 std_set.i 喜欢:

%{
#include <set>
#include <pair>
#include <stdexcept>
%}
namespace std {
template<class T> class set {
public:
  typedef T value_type;
  set();
  pair<iterator,bool> insert(const value_type& val); // iterator might be the difficulty here
}

或者为特定的模板实例创建包装器:

%rename(SetFoo) std::set<foo>;
class std::set<foo> {
public:
    set();
    std::pair<std::set<foo>::iterator,bool> insert(const &foo val); // std::set<foo>::iterator not known here...
};

在这两种情况下,我都被这个迭代器问题困扰,无法提供“简单”的解决方案。

我曾尝试与swig/Lib/std 一起玩,目前也没有成功。

【问题讨论】:

    标签: java c++ swig c++03


    【解决方案1】:

    我最终决定放弃迭代器并想出了一个简单的包装头来满足我的需要:

    #include <set>
    
    template<typename T>
    struct SetWrapper {
        SetWrapper() : data() {};
        void insert(const T& val) { data.insert(val); }
        std::set<T> data;
    };
    

    然后在界面中我们可以实例化不同版本的模板:

    %template(SetFoo) SetWrapper<Foo>;
    

    我必须注意参数中包含 std::set 的方法,我必须扩展如下类:

    struct A {
      A(const std::set& s); // this cannot be used directly unfortunately
    }
    
    %extend A {
      A(const SetWrapper& s) { // need a constructor with SetWrapper
        A *p = new A(s.data); // reuse the constructor above
        return p;
      }
    }
    

    【讨论】:

    • 您还对“更好”的解决方案感兴趣吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多