向 Python Swig 模板类添加新方法 [英] Add new method to a Python Swig Template class

查看:29
本文介绍了向 Python Swig 模板类添加新方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

%template(DoubleVector) vector<double>;

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

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?

我知道一个名为 %pythoncode 的标识符,但我无法使用它在此模板类中定义新函数.

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

推荐答案

给定一个接口文件,如:

Given an interface file like:

%module test

%{
#include <vector>
%}

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

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

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

它的优势在于它适用于您使用 SWIG 定位的任何语言,而不仅仅是 Python.

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

您也可以使用 %pythoncode 和一个未绑定的函数:

You can also do it using %pythoncode and an unbound 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
>>> 

这篇关于向 Python Swig 模板类添加新方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆