How To Pass Python List Address
I want to convert c++ code to python. I have created a python module using SWIG to access c++ classes. Now I want to pass the following c++ code to Python C++ #define LEVEL 3 dou
Solution 1:
Using raw double * and length as an interface is more difficult in SWIG. You'd need to write a typemap for the parameter pair that can intelligently read the array given the size. Easier to use SWIG's built-in vector support.
Example, with display support:
GradedDouble.i
%module GradedDouble
%{#include "GradedDouble.h"%}
%include <std_vector.i>%include <std_string.i>%template(DoubleVector) std::vector<double>;%rename(__repr__) ToString;%include "GradedDouble.h"
GradedDouble.h
#include<vector>#include<string>#include<sstream>classGradedDouble
{
std::vector<double> thre_;
public:
GradedDouble(const std::vector<double>& dbls) : thre_(dbls) {}
~GradedDouble() {}
std::string ToString()const{
std::ostringstream ss;
ss << "GradedDouble(";
for(auto d : thre_)
ss << ' ' << d;
ss << " )";
return ss.str();
}
};
Output
>>>import GradedDouble as gd>>>x=gd.GradedDouble([1.2,3.4,5.6])>>>x
GradedDouble( 1.2 3.4 5.6 )
Solution 2:
Another method for doing this is by using SWIG cpointer and carrays. Sample code is below:
Interface file:
%module example%include "cpointer.i"%{#include "Item.h"#include "GradedDouble.h"
extern void avg(double *buf);
%}%pointer_class(double, doublep);
%include "carrays.i"%array_class(double, doubleArray);%include <std_string.i>%include "Item.h"%include "GradedDouble.h"%template(Double) Item<double>;
Python code:
LEVEL = 3
thre = [1, 100, 10000]
a = example.doubleArray(LEVEL)
for i in xrange(LEVEL):
a[i] = thre[i]
gd=example.GradedDouble(LEVEL,a)
result = example.doublep()
gd.avg(result)
print result.value()
This worked for me
Post a Comment for "How To Pass Python List Address"