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.
_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
https://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to