2015-11-26 17 views
2
的矢量

隨着結構的vector一切正常javaout類型表不性病工作::指針

%include <std_vector.i> 

%typemap(javaout) const S1& std::vector<S1>::get { 
    //custom code 
} 

struct S1 {}; 
std::vector<S1> val; 

%template(vector_s1) std::vector<S1>; 

但不與指針的vector工作

%include <std_vector.i> 

%typemap(javaout) const S1*& std::vector<S1*>::get { 
    //custom code 
} 

struct S1 {}; 
std::vector<S1*> val; 

%template(vector_s1) std::vector<S1*>; 

樣品編譯swig -java -c++ -module sample sample.i

痛飲版本:

$ swig -version 

SWIG Version 3.0.7 

Compiled with i586-mingw32msvc-g++ [i586-pc-mingw32msvc] 

Configured options: +pcre 
+0

是什麼意思「沒有按」工作「? – sibnick

+0

@sibnick我得到默認的'vector_s1.get(int)'定義,而不是在typemap中指定。 – triclosan

+0

你可以指定swig版本嗎? – sibnick

回答

1

如果您有提供語言獨立包裝代碼爲std::vector文件swig/Lib/std/std_vector.i一看,你會發現這樣的評論:

// *** 
// This specialization should disappear or get simplified when 
// a 'const SWIGTYPE*&' can be defined 
// *** 
template<class _Tp, class _Alloc > 
class vector<_Tp*, _Alloc > { ... 

所以看來SWIG目前不能在你的上面的typemap定義中處理const S1*&

現在,提供用於std::vector的java包裝的文件swig/Lib/java/std_vector.i複雜得多,缺少專用於std::vector<T*>的文件。

增加這樣一個專業化自己應該解決您的問題:

文件std_vector_pointer.i

%include <std_vector.i> 
namespace std { 
template<class T> class vector<T*> { 
    public: 
    typedef size_t size_type; 
    typedef T* value_type; 
    typedef value_type const_reference; 
    vector(); 
    vector(size_type n); 
    size_type size() const; 
    size_type capacity() const; 
    void reserve(size_type n); 
    %rename(isEmpty) empty; 
    bool empty() const; 
    void clear(); 
    %rename(add) push_back; 
    void push_back(T* x); 
    %extend { 
     T* get(int i) throw (std::out_of_range) { 
      int size = int(self->size()); 
      if (i>=0 && i<size) 
       return (*self)[i]; 
      else 
       throw std::out_of_range("vector index out of range"); 
     } 
     void set(int i, T* val) throw (std::out_of_range) { 
      int size = int(self->size()); 
      if (i>=0 && i<size) 
       (*self)[i] = val; 
      else 
       throw std::out_of_range("vector index out of range"); 
     } 
    } 
}; 
} 

那麼下面應該爲你上面的例子中工作:

%include "std_vector_pointer.i" 

%typemap(javaout) S1* std::vector<S1*>::get { 
    //custom code 
} 

struct S1 {}; 
std::vector<S1*> val; 

%template(vector_s1) std::vector<S1*>; 
0

而不是使用原始指針,爲什麼不使用std :: shared_ptr?

此代碼應按照您期望的方式工作,您的「自定義代碼」將替換vector_s1.java中的get函數塊。

%module sample 

%include <std_vector.i> 
%include <std_shared_ptr.i> 

%{ 
#include <memory> 
%} 

%typemap(javaout) const std::shared_ptr<S1>& std::vector<std::shared_ptr<S1> >::get { 
    //custom code 
} 

struct S1 {}; 

%shared_ptr(s1); 
%template(vector_s1) std::vector<std::shared_ptr<S1> >; 
+0

不幸的是我無法更改cpp代碼。 – triclosan