-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPybind11VectorAndList.h
More file actions
104 lines (91 loc) · 2.63 KB
/
Pybind11VectorAndList.h
File metadata and controls
104 lines (91 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Copyright (C) 2019 EDF
// All Rights Reserved
// This code is published under the GNU Lesser General Public License (GNU LGPL)
#ifndef PYBIND11VECTORANDLIST_H
#define PYBIND11VECTORANDLIST_H
#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>
#include <pybind11/stl.h>
/// \brief Defines converter from list to c++ and c++ to list
// Vector to List
template< typename T>
struct VecToList
{
/// \brief Function
/// \param p_vec vector to convert to PyObject
/// \return a PyObject
static PyObject *convert(const std::vector< T> &p_vec)
{
pybind11::list *l = new pybind11::list();
for (size_t i = 0; i < p_vec.size(); i++)
{
(*l).append(p_vec[i]);
}
return l->ptr();
}
};
template< typename T>
struct VecToListShPtr
{
/// \brief Function
/// \param p_vec vector of shared_ptr to convert to PyObject
/// \return a PyObject
static PyObject *convert(const std::vector< std::shared_ptr< T> > &p_vec)
{
pybind11::list *l = new pybind11::list();
for (size_t i = 0; i < p_vec.size(); i++)
(*l).append(*p_vec[i]);
return l->ptr();
}
};
template< typename T, typename TT >
struct VecToListShPtrTtoTT
{
/// \brief Function
/// \param p_vec vector of shared_ptr to convert to PyObject
/// \return a PyObject
static PyObject *convert(const std::vector< std::shared_ptr< T> > &p_vec)
{
pybind11::list *l = new pybind11::list();
for (size_t i = 0; i < p_vec.size(); i++)
(*l).append(* std::static_pointer_cast<TT>(p_vec[i]));
return l->ptr();
}
};
// list of objects to vector of shared_ptr
template< typename T>
std::vector< std::shared_ptr< T > > convertFromListShPtr(const pybind11::list &ns)
{
std::vector< std::shared_ptr< T> > ret;
ret.reserve(ns.size());
for (auto item : ns)
{
T local = item.cast<T>() ;
ret.push_back(std::make_shared<T>(local));
}
return ret;
}
// converter list of objects to vector
template< typename T>
std::vector<T > convertFromList(const pybind11::list &ns)
{
std::vector< T > ret;
ret.reserve(ns.size());
for (auto item : ns)
{
T local = item.cast<T>() ;
ret.push_back(local);
}
return ret;
}
// same but send back a boost shared_ptr
template< typename T>
std::shared_ptr< std::vector<T > > convertFromListToShared(const pybind11::list &ns)
{
std::shared_ptr< std::vector<T > > ret = std::make_shared< std::vector<T> >() ;
ret->reserve(ns.size());
for (auto item : ns)
ret->push_back(item.cast<T>());
return ret;
}
#endif /* PYBIND11VECTORANDLIST_H */