我需要向我的 swig 模板类添加一个新方法,例如:
我在 myswig.i 中声明一个模板类,如下所示:
%template(DoubleVector) vector<double>;
这将在生成的 .py 文件中生成一个名为“DoubleVector”的类,并带有一些生成的方法。假设它们是 func1()、func2() 和 func3()。
这些是生成的函数,我无法控制它们。
现在,如果我想向此类(DoubleVector)添加一个名为“func4()”的新方法,我该怎么做?是否可以?
我知道一个名为 %pythoncode 的标识符,但我无法使用它在此模板类中定义新函数。
给定一个接口文件,例如:
%module test
%{
#include <vector>
%}
%include "std_vector.i"
%template(DoubleVector) std::vector<double>;
添加更多功能的最简单方法DoubleVector
是用C++编写,在SWIG接口文件中使用%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。
您也可以使用%pythoncode
and an 未绑定函数 https://stackoverflow.com/a/2982/168175:
%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
>>>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)