2012-01-12 66 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