在another question中,我学会了如何通过复制对象来公开将C ++对象返回给Python的函数。必须执行副本似乎不是最佳的。如何在不复制的情况下返回对象?即如何直接访问self.thisptr.getPeaks(data)
中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
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;
}
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
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
答案 0 :(得分:6)
如果你有一个现代的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
其次,创建一个矢量包装类。这定义了像列表一样访问它所必需的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()
然后定义包裹Peak
的类。这与您的其他类略有不同,因为它不拥有它包装的Peak
(向量确实)。否则,大多数功能保持不变
cdef class PyPeak2:
cdef Peak* thisptr
cdef PyPeakVector vector # keep this alive, since it owns the peak rather that PyPeak2
def __cinit__(self,PyPeakVector vec,idx):
self.vector = vec
self.thisptr = &vec.vec[idx]
# rest of functions as is
# don't define a destructor since we don't own the Peak
def 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()
最后,实施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
替代方法:
如果Peak
非常重要,那么当您构建move
时,您可以采用Peak
上的PyPeak
而不是矢量上的getPeaks
方法。对于你在这里的情况,移动和复制将相当于“峰值”。
如果您无法使用C ++ 11功能,则需要稍微更改一下界面。而不是让你的C ++ PyPeakVector
函数返回一个向量,它需要一个空向量引用(由input()
拥有)作为输入参数并写入它。其余大部分包装都保持不变。
答案 1 :(得分:-1)
有两个项目可以完成与C ++代码到Python的连接,它们经受了时间Boost.Python和SWIG的测试。两者都通过向相关的C / C ++代码添加额外的标记并生成动态加载的python扩展库(.so文件)和相关的python模块来工作。
但是,根据您的使用情况,可能仍有一些额外的标记看起来像“复制”。但是,复制不应该那么广泛,它将全部暴露在C ++代码中,而不是在Cython / Pyrex中逐字显式地复制。