platform independent and readable names for array export suffix

This commit is contained in:
Christopher Lackner 2019-09-11 13:04:50 +02:00
parent 59087f5c2c
commit 485d9f230b
2 changed files with 60 additions and 11 deletions

View File

@ -16,6 +16,56 @@ namespace ngcore
{ {
NGCORE_API extern bool ngcore_have_numpy; NGCORE_API extern bool ngcore_have_numpy;
// Python class name type traits
template <typename T>
struct PyNameTraits {
static const std::string & GetName()
{
static const std::string name =
py::cast<std::string>(py::cast(T()).attr("__class__").attr("__name__"));
return name;
}
};
template <typename T>
std::string GetPyName(const char *prefix = 0) {
std::string s;
if(prefix) s = std::string(prefix);
s+= PyNameTraits<T>::GetName();
return s;
}
template<>
struct PyNameTraits<int> {
static std::string GetName() { return "I"; }
};
template<>
struct PyNameTraits<unsigned> {
static std::string GetName() { return "U"; }
};
template<>
struct PyNameTraits<float> {
static std::string GetName() { return "F"; }
};
template<>
struct PyNameTraits<double> {
static std::string GetName() { return "D"; }
};
template<>
struct PyNameTraits<size_t> {
static std::string GetName() { return "S"; }
};
template<typename T>
struct PyNameTraits<std::shared_ptr<T>> {
static std::string GetName()
{ return std::string("sp_")+GetPyName<T>(); }
};
template<typename T> template<typename T>
Array<T> makeCArray(const py::object& obj) Array<T> makeCArray(const py::object& obj)
{ {
@ -50,9 +100,8 @@ namespace ngcore
{ {
using TFlat = FlatArray<T, TIND>; using TFlat = FlatArray<T, TIND>;
using TArray = Array<T, TIND>; using TArray = Array<T, TIND>;
std::string suffix = std::string(Demangle(typeid(T).name())) + "_" + Demangle(typeid(TIND).name()); std::string suffix = GetPyName<T>() + "_" +
std::replace(suffix.begin(), suffix.end(), ':', '_'); GetPyName<TIND>();
std::replace(suffix.begin(), suffix.end(), ' ', '_');
std::string fname = std::string("FlatArray_") + suffix; std::string fname = std::string("FlatArray_") + suffix;
auto flatarray_class = py::class_<TFlat>(m, fname.c_str(), auto flatarray_class = py::class_<TFlat>(m, fname.c_str(),
py::buffer_protocol()) py::buffer_protocol())

View File

@ -2,7 +2,7 @@ from pyngcore import *
from numpy import sort, array from numpy import sort, array
def test_array_numpy(): def test_array_numpy():
a = Array_int_unsigned_long(5) a = Array_I_S(5)
a[:] = 0 a[:] = 0
a[3:] = 2 a[3:] = 2
assert(sum(a) == 4) assert(sum(a) == 4)