如何在不复制对象的情况下公开将C++对象返回给Python的函数?

jul*_*jul 6 c++ python cython

另一个问题中,我学习了如何通过复制对象来公开将C++对象返回给Python的函数.必须执行副本似乎不是最佳的.如何在不复制的情况下返回对象?即如何直接访问self.thisptr.getPeaks(data)in 返回的峰值PyPeakDetection.getPeaks(在peak_detection_.pyx中定义)?

peak_detection.hpp

#ifndef PEAKDETECTION_H
#define PEAKDETECTION_H

#include <string>
#include <map>
#include <vector>

#include "peak.hpp"


class PeakDetection
{
    public:
        PeakDetection(std::map<std::string, std::string> config);
        std::vector<Peak> getPeaks(std::vector<float> &data);

    private:
        float _threshold;               
};

#endif
Run Code Online (Sandbox Code Playgroud)

peak_detection.cpp

#include <iostream>
#include <string>

#include "peak.hpp"
#include "peak_detection.hpp"


using namespace std;


PeakDetection::PeakDetection(map<string, string> config)
{   
    _threshold = stof(config["_threshold"]);
}

vector<Peak> PeakDetection::getPeaks(vector<float> &data){

    Peak peak1 = Peak(10,1);
    Peak peak2 = Peak(20,2);

    vector<Peak> test;
    test.push_back(peak1);
    test.push_back(peak2);

    return test;
}
Run Code Online (Sandbox Code Playgroud)

peak.hpp

#ifndef PEAK_H
#define PEAK_H

class Peak {
    public:
        float freq;
        float mag;

        Peak() : freq(), mag() {}
        Peak(float f, float m) : freq(f), mag(m) {}
};

#endif
Run Code Online (Sandbox Code Playgroud)

peak_detection_.pyx

# distutils: language = c++
# distutils: sources = peak_detection.cpp

from libcpp.vector cimport vector
from libcpp.map cimport map
from libcpp.string cimport string

cdef extern from "peak.hpp":
    cdef cppclass Peak:
        Peak()
        Peak(Peak &)
        float freq, mag


cdef class PyPeak:
    cdef Peak *thisptr

    def __cinit__(self):
        self.thisptr = new Peak()

    def __dealloc__(self):
        del self.thisptr

    cdef copy(self, Peak &other):
        del self.thisptr
        self.thisptr = new Peak(other)

    def __repr__(self):
        return "<Peak: freq={0}, mag={1}>".format(self.freq, self.mag)

    property freq:
        def __get__(self): return self.thisptr.freq
        def __set__(self, freq): self.thisptr.freq = freq

    property mag:
        def __get__(self): return self.thisptr.mag
        def __set__(self, mag): self.thisptr.mag = mag


cdef extern from "peak_detection.hpp":
    cdef cppclass PeakDetection:
        PeakDetection(map[string,string])
        vector[Peak] getPeaks(vector[float])

cdef class PyPeakDetection:
    cdef PeakDetection *thisptr

    def __cinit__(self, map[string,string] config):
        self.thisptr = new PeakDetection(config)

    def __dealloc__(self):
        del self.thisptr

    def getPeaks(self, data):
        cdef Peak peak
        cdef PyPeak new_peak
        cdef vector[Peak] peaks = self.thisptr.getPeaks(data)

        retval = []

        for peak in peaks:
            new_peak = PyPeak()
            new_peak.copy(peak) # how can I avoid that copy?
            retval.append(new_peak)

        return retval
Run Code Online (Sandbox Code Playgroud)

Dav*_*idW 7

如果你有一个现代的C++编译器并且可以使用rvalue引用,那么移动构造函数和std :: move它是非常简单的.我认为最简单的方法是为向量创建一个Cython包装器,然后使用移动构造函数来捕获向量的内容.

显示的所有代码都在peak_detection_.pyx中.

首先包装std::move.为简单起见,我只是包装了我们想要的一个案例(vector<Peak>),而不是搞乱模板.

cdef extern from "<utility>":
    vector[Peak]&& move(vector[Peak]&&) # just define for peak rather than anything else
Run Code Online (Sandbox Code Playgroud)

其次,创建一个矢量包装类.这定义了像列表一样访问它所必需的Python函数.它还定义了一个调用移动赋值运算符的函数

cdef class PyPeakVector:
    cdef vector[Peak] vec

    cdef move_from(self, vector[Peak]&& move_this):
        self.vec = move(move_this)

    def __getitem__(self,idx):
        return PyPeak2(self,idx)

    def __len__(self):
        return self.vec.size()
Run Code Online (Sandbox Code Playgroud)

然后定义包装的类Peak.这与你的其他类略有不同,因为它不拥有Peak它的包装(向量确实).否则,大多数功能保持不变

cdef class PyPeak2:
    cdef int idx
    cdef PyPeakVector vector # keep this alive, since it owns the peak rather that PyPeak2

    def __cinit__(self,PyPeakVector vec,idx):
        self.vector = vec
        self.idx = idx

    cdef Peak* getthisptr(self):
        # lookup the pointer each time - it isn't generally safe
        # to store pointers incase the vector is resized
        return &self.vector.vec[self.idx]

    # rest of functions as is

    # don't define a destructor since we don't own the Peak
Run Code Online (Sandbox Code Playgroud)

最后,实施 getPeaks()

cdef class PyPeakDetection:
    # ...    
    def getPeaks(self, data):
        cdef Peak peak
        cdef PyPeak new_peak
        cdef vector[Peak] peaks = self.thisptr.getPeaks(data)

        retval = PyPeakVector()
        retval.move_from(move(peaks))

        return retval
Run Code Online (Sandbox Code Playgroud)

替代方法:

如果Peak是平凡的,你可以去那里你调用一个方法movePeak而上的向量,为您建造PyPeak秒.对于你在这里的情况,移动和复制将相当于"峰值".

如果您不能使用C++ 11功能,则需要稍微更改一下界面.而不是让你的C++ getPeaks函数返回一个向量,它需要一个空的向量引用(拥有PyPeakVector)作为输入参数并写入它.其余的大部分包装都是一样的.