From 179be0d519be2b4e0ec68c1970460ef6e0342288 Mon Sep 17 00:00:00 2001 From: Joakim Hove Date: Wed, 30 Oct 2019 22:34:37 +0100 Subject: [PATCH] Add converter to convert CHAR arrays --- CMakeLists_files.cmake | 1 + python/cxx/converters.cpp | 22 ++++++++++++++++++++++ python/cxx/converters.hpp | 2 ++ python/setup.py | 1 + 4 files changed, 26 insertions(+) create mode 100644 python/cxx/converters.cpp diff --git a/CMakeLists_files.cmake b/CMakeLists_files.cmake index 3541dd5c9..2f79ecb1d 100644 --- a/CMakeLists_files.cmake +++ b/CMakeLists_files.cmake @@ -180,6 +180,7 @@ if(ENABLE_ECL_INPUT) # setup.py file. list( APPEND PYTHON_CXX_SOURCE_FILES python/cxx/connection.cpp + python/cxx/converters.cpp python/cxx/deck.cpp python/cxx/deck_keyword.cpp python/cxx/eclipse_3d_properties.cpp diff --git a/python/cxx/converters.cpp b/python/cxx/converters.cpp new file mode 100644 index 000000000..f2a617aae --- /dev/null +++ b/python/cxx/converters.cpp @@ -0,0 +1,22 @@ +#include "converters.hpp" + +namespace convert { + +py::array numpy_string_array(const std::vector& input) { + const std::size_t target_length = 8; + using numpy_string_t = char[target_length]; + auto output = py::array_t(input.size()); + auto output_ptr = reinterpret_cast(output.request().ptr); + for (std::size_t index = 0; index < input.size(); index++) { + if (input[index].size() > target_length) + throw std::invalid_argument("Current implementation only works with 8 character strings"); + + std::size_t length = input[index].size(); + std::strncpy(output_ptr[index], input[index].c_str(), length); + for (std::size_t i = length; i < target_length; i++) + output_ptr[index][i] = '\0'; + } + return output; +} + +} diff --git a/python/cxx/converters.hpp b/python/cxx/converters.hpp index af701a682..5de759065 100644 --- a/python/cxx/converters.hpp +++ b/python/cxx/converters.hpp @@ -23,6 +23,8 @@ std::string str( const T& t ) { namespace convert { +py::array numpy_string_array(const std::vector& input); + template std::vector vector(py::array_t& input) { T * input_ptr = (T *) input.request().ptr; diff --git a/python/setup.py b/python/setup.py index 283e53e59..74d97857f 100644 --- a/python/setup.py +++ b/python/setup.py @@ -36,6 +36,7 @@ ext_modules = [ [ 'cxx/unit_system.cpp', 'cxx/connection.cpp', + 'cxx/converters.cpp', 'cxx/deck.cpp', 'cxx/deck_keyword.cpp', 'cxx/eclipse_3d_properties.cpp',