[C++-sig] Copying string values to ndarray using Boost.Python
Mohan Varma
mohan.varma at gmail.com
Wed Jan 31 10:07:03 EST 2018
I have been trying to create an ndarray in C++ using Boost.Python while
creating a Python module. The ndarray object is created using a composite
dtype with an int value column, a 32-byte string column and a float value
column. I am able to set the values for int and float columns and access
them in Python. I am not sure on how to set the string column values in
C++. Here is the synopsis of my code, I believe it explains the problem
fairly well. Any help in this regard is greatly appreciated.
struct Test
{
int id;
std::string name;
float value;
};
std::vector<Test> test_values;
//
namespace bp = boost::python;
namespace np = boost::python::numpy;
//
//
bp::tuple shape = bp::make_tuple(test_values.size());
bp::list list_for_dtype;
list_for_dtype.append(bp::make_tuple("id",np::dtype::get_builtin<int>()));
list_for_dtype.append(bp::make_tuple("name", np::dtype(bp::str("U32"))));
list_for_dtype.append(bp::make_tuple("value",np::dtype::get_builtin<float>()));
np::dtype custom_dtype = np::dtype(list_for_dtype);
int item_size = custom_dtype.get_itemsize();
np::ndarray values_array = np::zeros(shape, custom_dtype);
char * dest_ptr = (char *) values_array .get_data();
for (size_t i = 0; i < test_values.size(); ++i) {
memcpy((void *) dest_ptr, &test_values[i].id, sizeof(int));
dest_ptr += sizeof(int);
// How do I copy the string value to ndarray buffer?
//bp::str bpname(&test_values[i].name);
//memcpy((void *) dest_ptr, bpname.ptr(), sizeof(float));
dest_ptr += 32 * 4;
memcpy((void *) dest_ptr, &test_values[i].value, sizeof(float));
dest_ptr += sizeof(float);
}
Thank you,
Mohan.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20180131/01a673b2/attachment.html>
More information about the Cplusplus-sig
mailing list