将新方法添加到Python Swig Template类

Sau*_*abh 5 python swig templates

我需要在swig模板类中添加一个新方法,例如:

我在myswig.i中声明了一个模板类,如下所示:

%template(DoubleVector) vector<double>;
Run Code Online (Sandbox Code Playgroud)

这将在生成的.py文件中生成一个名为"DoubleVector"的类,其中包含一些生成的方法.假设它们是func1(),func2()和func3().这些是生成的函数,我无法控制它们.现在,如果我想向这个类(DoubleVector)添加一个名为"func4()"的新方法,我该怎么办呢?可能吗?

我知道一个名为%pythoncode的标识符,但我不能用它来定义这个模板类中的新函数.

Fle*_*exo 9

给定一个接口文件,如:

%module test

%{
#include <vector>
%}

%include "std_vector.i"
%template(DoubleVector) std::vector<double>;
Run Code Online (Sandbox Code Playgroud)

添加更多功能的最简单方法DoubleVector是使用%extend以下方法在SWIG接口文件中使用C++编写它:

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

这样做的好处是它适用于您使用SWIG定位的任何语言,而不仅仅是Python.

您也可以使用%pythoncode未绑定的功能:

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

DoubleVector.foo = foo
%}
Run Code Online (Sandbox Code Playgroud)

运行此示例:

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
>>> 
Run Code Online (Sandbox Code Playgroud)