Skip to content

Commit

Permalink
support convert StringDType to R character vectors
Browse files Browse the repository at this point in the history
  • Loading branch information
t-kalinowski committed Jun 18, 2024
1 parent d2a3b94 commit bc2d4c7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/libpython.h
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,8 @@ enum NPY_TYPES {
NPY_NOTYPE,
NPY_CHAR,
NPY_USERDEF=256,
NPY_NTYPES_ABI_COMPATIBLE=21
NPY_NTYPES_ABI_COMPATIBLE=21,
NPY_VSTRING=2056 // (added in NumPy 2.0), StringDType
};


Expand Down
13 changes: 12 additions & 1 deletion src/python.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,7 @@ int narrow_array_typenum(int typenum) {
case NPY_STRING:
case NPY_UNICODE:
case NPY_OBJECT:
case NPY_VSTRING:
break;

// unsupported
Expand Down Expand Up @@ -1553,16 +1554,26 @@ SEXP py_to_r_cpp(PyObject* x, bool convert, bool simple) {
}

case NPY_STRING:
case NPY_VSTRING:
case NPY_UNICODE: {

PyObjectPtr nditerArgs(PyTuple_New(1));
static PyObject* nditerArgs = []() {
PyObject* flags = PyTuple_New(1);
// iterating over a StringDType requires us to pass 'refs_ok' flag,
// since StringDTypes are really refs under the hood.
PyTuple_SetItem(flags, 0, as_python_str("refs_ok")); // steals ref
PyObject* args = PyTuple_New(2);
PyTuple_SetItem(args, 1, flags); // steals ref
return args;
}();
// PyTuple_SetItem steals reference the array, but it's already wraped
// into PyObjectPtr earlier (so it gets deleted after the scope of this function)
// To avoid trying to delete it twice, we need to increase its ref count here.
PyTuple_SetItem(nditerArgs, 0, (PyObject*)array);
Py_IncRef((PyObject*)array);

PyObjectPtr iter(PyObject_Call(get_np_nditer(), nditerArgs, NULL));
PyTuple_SetItem(nditerArgs, 0, NULL); // clear ref to array

if (iter.is_null()) {
throw PythonException(py_fetch_error());
Expand Down

0 comments on commit bc2d4c7

Please sign in to comment.