簡體   English   中英

Swig shared_ptr宏與模板類和派生類

[英]Swig shared_ptr macro with templated class and derived classes

這個問題在某種程度上是這里發布的問題的擴展: 具有模板類的SWIG_SHARED_PTR宏雖然問題可能完全不相關。

基本設置是這樣的:我試圖讓SWIG將模板化的類包裝為shared_ptr。 所以接口文件看起來應該是這樣的

%shared_ptr(template_instance)
%include template_class.cpp
%template(vector_instance) template_class<int>;

現在的問題是template_class有很多派生類,這會在swig中引發很多警告,然后構建錯誤。 這些類不需要作為shared_ptr處理,所以我寧願忽略上面代碼生成的警告。 錯誤的解決方案似乎是:

%shared_ptr(template_derived1)
%shared_ptr(template_derived2)
.
.
.
%shared_ptr(template_derivedn)
%shared_ptr(template_instance)
%include template_class.cpp
%template(vector_instance) template_class<int>;

這是有效的,但是是一個巨大的混亂,並且我認為將所有內容表示為shared_ptr(它是什么?)必然存在一些缺點。 這附近有人嗎?

編輯:更新具體示例

test.h

class Base
{
  int base_member;
};

class Derived : public Base
{
  int derived_member;
};

test.i

%module test
%{
#include "test.h"
#include <boost/shared_ptr.hpp>
  %}

%include <boost_shared_ptr.i>
%shared_ptr(Base)
%include test.h

命令:

swig -python -c++ test.i 
g++ -fPIC -I /usr/include/python2.7 -c test_wrap.cxx

在這個精簡的示例中,swig調用會發出警告,而g ++調用會產生錯誤。 請注意,我刪除了模板,因為它似乎不是問題的一個組成部分。

通過注釋解決錯誤

%shared_ptr(Base)

swig生成的警告是:

test.h:10: Warning 520: Derived class 'Derived' of 'Base' is not similarly marked as a smart pointer

而g ++的錯誤是:

test_wrap.cxx: In function ‘PyObject* _wrap_delete_Derived(PyObject*, PyObject*)’:
test_wrap.cxx:3155:22: error: ‘smartarg1’ was not declared in this scope

這里的警告是因為你需要告訴SWIG關於整個類層次結構,而不僅僅是基類,以便能夠有效地使用智能指針。 它需要能夠在智能指針之間進行轉換,以便任何采用指向Base的智能指針的東西也可以接受一個到Derived 所以你的界面文件需要是:

%module test
%{
#include "test.h"
#include <boost/shared_ptr.hpp>
%}

%include <boost_shared_ptr.i>
%shared_ptr(Base)
%shared_ptr(Derived)
%include "test.h"

這解決了被警告的問題並生成了在我的機器上編譯好的代碼。

如果您不想告訴SWIG所有派生類型,最簡單的方法是從SWIG中完全隱藏類型 - 只從您想要包裝的東西中公開Base類型。 您可以通過幾種方式實現這一點,最不具侵入性的是將接口文件更改為:

%module test
%{
#include "test.h"
#include <boost/shared_ptr.hpp>
%}

%include <boost_shared_ptr.i>
%ignore Derived;
%shared_ptr(Base)
%include "test.h"

這會導致只包裝Base ,因此無法生成無法編譯的代碼。

或者,因為每個類型仍需要%ignore ,您可以修改頭文件以完全隱藏Derived自SWIG的聲明/定義:

class Base
{
  int base_member;
};
#ifndef SWIG
class Derived : public Base
{
  int derived_member;
};
#endif

如果你的項目被組織起來,每個類型(粗略地)有一個頭文件,你可以通過簡單地不使用%include和基本文件以外的文件來更簡單地執行此操作。

如果你仍然想要包裝它們,但不是作為smart_ptr,我認為你將不得不接受將會有很多%smart_ptr - 你可以自動生成它們嗎? 您可能可以使用模塊玩游戲,但我認為這不會輕松或值得付出努力。

暫無
暫無

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

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