Add new method to a Python Swig Template class

佐手、 提交于 2019-12-10 14:25:58

问题


I need to add a new method to my swig template class, for example:

I am declaring a template class in myswig.i as follows:

%template(DoubleVector) vector<double>;

this will generate a class named "DoubleVector" in the generated .py file with some generated methods. lets suppose they are func1(), func2() and func3(). These are generated functions and i have no control over them. Now, if I want to add a new method called "func4()" to this class(DoubleVector), how may I do it? Is it possible?

I know of a identifier called %pythoncode but I could not use it to define a new function in this template class.


回答1:


Given an interface file like:

%module test

%{
#include <vector>
%}

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

The easiest way to add more functionality to DoubleVector is to write it in C++, in the SWIG interface file using %extend:

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

this has the advantage that it would work for any language you target with SWIG, not just Python.

You can also do it using %pythoncode and an unbound function:

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

DoubleVector.foo = foo
%}

Example running this:

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
>>> 


来源:https://stackoverflow.com/questions/8837135/add-new-method-to-a-python-swig-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!