How to pass python list address

2024/11/16 7:23:55

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 3double thre[LEVEL] = { 1.0l, 1.0e+2, 1.0e+5 };GradedDouble gd(LEVEL, thre);gd.avg(thre);

I need to convert the above code to python

C++ constructor used for generating python module

GradedDouble::GradedDouble(int n, double *thre)
{n_ = n;for (int i = 0; i < n_; ++i){thre_.push_back(thre[i]);grade_.push_back(new grade_type());}
}

SWIG interface file

/* File: 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> >;

A sample python module function

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_reprdef __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)

How do I convert it?

Answer

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>class GradedDouble
{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 )
https://en.xdnf.cn/q/119217.html

Related Q&A

Python open says file doesnt exist when it does

I am trying to work out why my Python open call says a file doesnt exist when it does. If I enter the exact same file url in a browser the photo appears.The error message I get is:No such file or direc…

How to map one list and dictionary in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 4 years ago.Improve…

Sorting date inside of files (Python)

I have a txt file with names and dates like this name0 - 05/09/2020 name1 - 14/10/2020 name2 - 02/11/2020 How can I sort the text file by date? so that the file will end up like this name2 - 02/11/202…

Dicing in python

Code:-df = pd.DataFrame({col1:t, col2:wordList}) df.columns=[DNT,tweets] df.DNT = pd.to_datetime(df.DNT, errors=coerce) check=df[ (df.DNT < 09:20:00) & (df.DNT > 09:00:00) ]Dont know why this…

How to collect all specified hrefs?

In this test model I can collect the href value for the first (tr, class_=rowLive), Ive tried to create a loop to collect all the others href but it always gives IndentationError: expected an indented …

How do I sort data highest to lowest in Python from a text file?

I have tried multiple methods in doing this but none of them seem to work The answer comes up alphabetically insteadf=open("class2.txt", "r") scores=myfile.readlines() print(sorted(…

Determine if a variable is an instance of any class

How to determine if a variable is an instance in Python 3? I consider something to be an instance if it has __dict__ attribute.Example:is_instance_of_any_class(5) # should return False is_instance_of…

Method POST not allowed with Django Rest Framework

Im trying to create a JSON API compliant rest service using Django Rest Framework JSON API: https://django-rest-framework-json-api.readthedocs.io/en/stable/index.htmlI think Im stuck at the Django Rest…

Running multiple queries in mongo`

I have a collection and want to get a set of results that met a set of conditions. I understand the Mongo doesnt let you use joins so I would need to run separate queries and join the results into a si…

Error in Calculating neural network Test Accuracy

I tried to train my neural network, and then evaluate its testing accuracy. I am using the code at the bottom of this post to train. The fact is that for other neural networks, I can evaluate the testi…