Mantid
Loading...
Searching...
No Matches
PySequenceToVector.h
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2011 ISIS Rutherford Appleton Laboratory UKRI,
4// NScD Oak Ridge National Laboratory, European Spallation Source,
5// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6// SPDX - License - Identifier: GPL - 3.0 +
7#pragma once
8
9#include <boost/python/extract.hpp>
10#include <boost/python/object.hpp>
11#include <vector>
12
13#include <string>
14
15namespace Mantid {
16namespace PythonInterface {
17namespace // <anonymous>
18{
22template <typename CType> struct ExtractCType {
28 inline CType operator()(PyObject *value) { return boost::python::extract<CType>(value); }
29};
30
34template <> struct ExtractCType<std::string> {
40 inline std::string operator()(PyObject *value) { return boost::python::extract<std::string>(PyObject_Str(value)); }
41};
42
43} // namespace
44
45namespace Converters {
50template <typename DestElementType> struct PySequenceToVector {
51 // Alias definitions
52 using TypedVector = std::vector<DestElementType>;
53
54 PySequenceToVector(const boost::python::object &value) : m_obj(value) {}
55
62 TypedVector cvector(srcSize());
63 copyTo(cvector);
64 return cvector;
65 }
66
71 inline void copyTo(TypedVector &dest) {
73 ExtractCType<DestElementType> elementConverter;
74 auto length = srcSize();
75 for (size_t i = 0; i < length; ++i) {
76 dest[i] = elementConverter(PySequence_GetItem(ptr(), i));
77 }
78 }
79
80private:
81 inline PyObject *ptr() const { return m_obj.ptr(); }
82
83 inline std::size_t srcSize() const { return static_cast<size_t>(PySequence_Size(ptr())); }
84
85 inline void throwIfSizeMismatched(const TypedVector &dest) const {
86 if (srcSize() != dest.size()) {
87 throw std::invalid_argument("Length mismatch between python list & C array. python=" + std::to_string(srcSize()) +
88 ", C=" + std::to_string(dest.size()));
89 }
90 }
91
93 boost::python::object m_obj;
94};
95} // namespace Converters
96} // namespace PythonInterface
97} // namespace Mantid
double value
The value of the point.
Definition FitMW.cpp:51
Helper class which provides the Collimation Length for SANS instruments.
STL namespace.
std::string to_string(const wide_integer< Bits, Signed > &n)
Converts a Python sequence type to a C++ std::vector, where the element type is defined by the templa...
void throwIfSizeMismatched(const TypedVector &dest) const
TypedVector operator()()
Converts the Python object to a C++ vector.
void copyTo(TypedVector &dest)
Fill the container with data from the array.
boost::python::object m_obj
Python object to convert.