我想把c++代码转换成python。 我用SWIG创建了一个python模块来访问c++类。在
现在我想把下面的c++代码传递给Python
C++ +<
#define LEVEL 3
double thre[LEVEL] = { 1.0l, 1.0e+2, 1.0e+5 };
GradedDouble gd(LEVEL, thre);
gd.avg(thre);
我需要把上面的代码转换成python
< P> C++构造函数用于生成Python模块 ^{pr2}$SWIG接口文件
/*文件:example.i*/
%module example
%include typemaps.i
%apply double * INPUT { double *}
%apply double * INPUT { double *buf };
%{
#include "Item.h"
#include "GradedComplex.h"
#include "GradedDouble.h"
void avg(double *buf);
%}
%include <std_string.i>
%include <std_complex.i>
%include "Item.h"
%include "GradedComplex.h"
%include "GradedDouble.h"
%template(Int) Item<int>;
%template(Double) Item<double>;
%template(Complex) Item<std::complex<double> >;
python模块函数示例
class GradedDouble(_object):
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, GradedDouble, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, GradedDouble, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _example.new_GradedDouble(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _example.delete_GradedDouble
__del__ = lambda self : None;
def push(self, *args): return _example.GradedDouble_push(self, *args)
def avg(self, *args): return _example.GradedDouble_avg(self, *args)
GradedDouble_swigregister = _example.GradedDouble_swigregister
GradedDouble_swigregister(GradedDouble)
如何转换?在
另一种方法是使用swigcpointer和carrays。示例代码如下:
接口文件:
Python代码:
^{pr2}$这对我有用
在SWIG中,使用raw double*和length作为接口比较困难。您需要为参数对编写一个typemap,它可以智能地读取给定大小的数组。更容易使用SWIG的内置向量支持。在
示例,支持显示:
等级二倍。i
等级二倍.h
^{pr2}$输出
相关问题 更多 >
编程相关推荐