Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you wrap C++ code for IronPython access

I have a simple example which I want to access from Ironpython (I am coming from 'regular/sane' python') so I am struggling importing my C++ code into Ironpython. Normally I just use SWIG, wrap my code, import and go on my merry way

But with Ironpython being C# and not C based it makes this process much harder

How do I wrap this class for ironpython (I also attached my swig file for this example, but that might not be useful)

#include "minimal.h"


double average(std::vector<int> v) {
    return std::accumulate(v.begin(), v.end(), 0.0) / v.size();
}

std::vector<double> half(const std::vector<double>& v) {
    std::vector<double> w(v);
    for (unsigned int i = 0; i<w.size(); i++)
        w[i] /= 2.0;
    return w;
}

void halve_in_place(std::vector<double>& v) {
    std::transform(v.begin(), v.end(), v.begin(),
        std::bind2nd(std::divides<double>(), 2.0));
}

with the header file

#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>

double average(std::vector<int> v);

std::vector<double> half(const std::vector<double>& v);

void halve_in_place(std::vector<double>& v);

I had a swig i file minimal.i but realize there are numerous issues issuing a swig.exe -c++ -python "%(FullPath)" on this and having ironpython actually accept it on import.

%module transfervector
%{
#include "minimal.h"
%}

%include "std_vector.i"
// Instantiate templates used by example
namespace std {
   %template(IntVector) vector<int>;
   %template(DoubleVector) vector<double>;
}

// Include the header file with above prototypes
%include "minimal.h"
like image 483
Joe Avatar asked Nov 01 '22 19:11

Joe


1 Answers

SWIG-python isn't going to work - it generates CPython extensions, and IronPython doesn't support those.

Ultimately you'll need to wrap the C++ so that it's accessible from .NET. I think you can use SWIG to generate C# wrappers, which you could then import into IronPython. Otherwise, you might be able to compile with the C++/CLI compiler to generate a .NET assembly directly, which can also be used from IronPython.

like image 189
Jeff Hardy Avatar answered Nov 15 '22 03:11

Jeff Hardy