2012-01-12 62 views
5

我需要一個新的方法添加到我痛飲模板類,例如:新的方法添加到一個Python痛飲模板類

我聲明在myswig.i模板類,如下所示:

%template(DoubleVector) vector<double>; 

這將在生成的.py文件中使用一些生成的方法生成一個名爲「DoubleVector」的類。讓我們假設它們是func1(),func2()和func3()。 這些是生成的函數,我無法控制它們。 現在,如果我想爲這個類(DoubleVector)添加一個名爲「func4()」的新方法,我該怎麼做?可能嗎?

我知道一個名爲%pythoncode的標識符,但我無法用它來定義此模板類中的新函數。

+0

我假設你的意思是'%模板(DoubleVector)載體;'? – Flexo 2012-01-12 16:41:15

+0

雅,我很抱歉,我的意思%模板(DoubleVector)載體;只要。 謝謝:) – Saurabh 2012-01-12 19:07:59

回答

9

給定一個接口文件,如:

%module test 

%{ 
#include <vector> 
%} 

%include "std_vector.i" 
%template(DoubleVector) std::vector<double>; 

更多的功能添加到DoubleVector最簡單的方法是使用%extend把它寫在C++中,SWIG接口文件:

%extend std::vector<double> { 
    void bar() { 
    // don't for get to #include <iostream> where you include vector: 
    std::cout << "Hello from bar" << std::endl;  
    } 
} 

這有它的優勢在於它適用於您使用SWIG定位的任何語言,而不僅僅是Python。

你也可以做到這一點使用%pythoncodeunbound function

%pythoncode %{ 
def foo (self): 
     print "Hello from foo" 

DoubleVector.foo = foo 
%} 

實例運行以下命令:

Python 2.6.7 (r267:88850, Aug 11 2011, 12:16:10) 
[GCC 4.6.1] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import test 
>>> d = test.DoubleVector() 
>>> d.foo() 
Hello from foo 
>>> d.bar() 
Hello from bar 
>>> 
+1

訣竅是'%extend'完整的模板名稱,而不是縮寫名稱。例如,'%extend std :: vector ',而不是'%extend DoubleVector'。 – 2013-07-22 23:22:31

+0

@Paul你也可以在沒有名字的類定義中使用%extend,它適用於當前類。 swig庫使用了這一點。 – Flexo 2013-07-23 06:55:52

+1

除了無界函數之外,似乎也可以將'%pythoncode'嵌套到'%extend'塊中:'%extend std :: vector {%pythoncode%{def foo(self):pass %}};' – user1556435 2018-01-01 12:56:09