簡體   English   中英

使用SWIG和C ++的std :: map時沒有Java的迭代器

[英]No iterator for Java when using SWIG with C++'s std::map

我在C ++中實現了一個帶有std::map的類,並使用SWIG創建了從Java調用的接口。 但是沒有迭代器對象允許我遍歷SWIG包裝的std::map的條目。 有誰知道如何創建迭代器?

為了能夠在Java中迭代Object,它需要實現Iterable 這又需要一個名為iterator()的成員函數,它返回一個合適的Iterator實現。

從你的問題來看,你不清楚你在地圖中使用的是什么類型,以及你是否希望能夠迭代對(如在C ++中),鍵或值。 三種變體的解決方案基本相似,下面我的例子選擇了值。

首先,我用來測試這個SWIG接口文件的前導碼:

%module test

%include "std_string.i"
%include "std_map.i"

為了實現可迭代的映射,我已經聲明,定義並包裝了SWIG接口文件中的另一個類。 這個類, MapIterator為我們實現了Iterator接口。 它是Java和包裝C ++的混合體,其中一個比另一個更容易編寫。 首先是一些Java,一個類型映射,它給它實現的接口,然后是Iterable接口所需的三個方法中的兩個,作為一個typemap給出:

%typemap(javainterfaces) MapIterator "java.util.Iterator<String>"
%typemap(javacode) MapIterator %{
  public void remove() throws UnsupportedOperationException {
    throw new UnsupportedOperationException();
  }

  public String next() throws java.util.NoSuchElementException {
    if (!hasNext()) {
      throw new java.util.NoSuchElementException();
    }

    return nextImpl();
  }
%}

然后我們提供MapIterator的C ++部分,它具有除了拋出next()部分的異常以及迭代器所需的狀態(用std::map自己的const_iterator表示next()之外的所有私有實現。

%javamethodmodifiers MapIterator::nextImpl "private";
%inline %{
  struct MapIterator {
    typedef std::map<int,std::string> map_t;
    MapIterator(const map_t& m) : it(m.begin()), map(m) {}
    bool hasNext() const {
      return it != map.end();
    }

    const std::string& nextImpl() {
      const std::pair<int,std::string>& ret = *it++;
      return ret.second;
    }
  private:
    map_t::const_iterator it;
    const map_t& map;    
  };
%}

最后我們需要告訴SWIG我們正在包裝的std::map實現了Iterable接口並提供了一個額外的成員函數,用於包裝std::map ,它返回我們剛寫的MapIterator類的新實例:

%typemap(javainterfaces) std::map<int,std::string> "Iterable<String>"

%newobject std::map<int,std::string>::iterator() const;
%extend std::map<int,std::string> {
  MapIterator *iterator() const {
    return new MapIterator(*$self);
  }
}

%template(MyMap) std::map<int,std::string>;

這可能是更通用的,例如用宏來隱藏地圖的類型,這樣如果你有多個地圖,那么就像使用%template一樣“調用”適當地圖的宏。

原始類型的映射也有一點點復雜 - 你需要安排Java端使用Double / Integer而不是double / int (我相信是自動裝箱這個術語),除非你決定在這種情況下包裝對你可以與原始成員配對。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM