Prototyping with Python code before compiling

前端 未结 7 1380
囚心锁ツ
囚心锁ツ 2021-01-30 17:56

I have been mulling over writing a peak-fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I ma

7条回答
  •  佛祖请我去吃肉
    2021-01-30 18:50

    I haven't used SWIG or SIP, but I find writing Python wrappers with boost.python to be very powerful and relatively easy to use.

    I'm not clear on what your requirements are for passing types between C/C++ and python, but you can do that easily by either exposing a C++ type to python, or by using a generic boost::python::object argument to your C++ API. You can also register converters to automatically convert python types to C++ types and vice versa.

    If you plan use boost.python, the tutorial is a good place to start.

    I have implemented something somewhat similar to what you need. I have a C++ function that accepts a python function and an image as arguments, and applies the python function to each pixel in the image.

    Image* unary(boost::python::object op, Image& im)
    {
        Image* out = new Image(im.width(), im.height(), im.channels());
        for(unsigned int i=0; i(op(im[i]));
        }
        return out;
    }
    

    In this case, Image is a C++ object exposed to python (an image with float pixels), and op is a python defined function (or really any python object with a __call__ attribute). You can then use this function as follows (assuming unary is located in the called image that also contains Image and a load function):

    import image
    im = image.load('somefile.tiff')
    double_im = image.unary(lambda x: 2.0*x, im)
    

    As for using arrays with boost, I personally haven't done this, but I know the functionality to expose arrays to python using boost is available - this might be helpful.

提交回复
热议问题