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
10#include <boost/python/extract.hpp>
11#include <boost/python/object.hpp>
12#include <vector>
13
14namespace Mantid {
15namespace PythonInterface {
16namespace // <anonymous>
17{
21template <typename CType> struct ExtractCType {
27 inline CType operator()(PyObject *value) { return boost::python::extract<CType>(value); }
28};
29
33template <> struct ExtractCType<std::string> {
39 inline std::string operator()(PyObject *value) { return boost::python::extract<std::string>(PyObject_Str(value)); }
40};
41
42} // namespace
43
44namespace Converters {
49template <typename DestElementType> struct DLLExport PySequenceToVector {
50 // Alias definitions
51 using TypedVector = std::vector<DestElementType>;
52
53 PySequenceToVector(const boost::python::object &value) : m_obj(value) {}
54
61 TypedVector cvector(srcSize());
62 copyTo(cvector);
63 return cvector;
64 }
65
70 inline void copyTo(TypedVector &dest) {
71 throwIfSizeMismatched(dest);
72 ExtractCType<DestElementType> elementConverter;
73 auto length = srcSize();
74 for (size_t i = 0; i < length; ++i) {
75 dest[i] = elementConverter(PySequence_GetItem(ptr(), i));
76 }
77 }
78
79private:
80 inline PyObject *ptr() const { return m_obj.ptr(); }
81
82 inline std::size_t srcSize() const { return static_cast<size_t>(PySequence_Size(ptr())); }
83
84 inline void throwIfSizeMismatched(const TypedVector &dest) const {
85 if (srcSize() != dest.size()) {
86 throw std::invalid_argument("Length mismatch between python list & C array. python=" + std::to_string(srcSize()) +
87 ", C=" + std::to_string(dest.size()));
88 }
89 }
90
92 boost::python::object m_obj;
93};
94} // namespace Converters
95} // namespace PythonInterface
96} // namespace Mantid
double value
The value of the point.
Definition: FitMW.cpp:51
#define DLLExport
Definitions of the DLLImport compiler directives for MSVC.
Definition: System.h:53
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.
PySequenceToVector(const boost::python::object &value)
void copyTo(TypedVector &dest)
Fill the container with data from the array.
boost::python::object m_obj
Python object to convert.