Skip to content

Instantly share code, notes, and snippets.

@qunaibit
Created June 4, 2022 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qunaibit/5c2314c3e4ae3b44821f0d8da1fecf32 to your computer and use it in GitHub Desktop.
Save qunaibit/5c2314c3e4ae3b44821f0d8da1fecf32 to your computer and use it in GitHub Desktop.
HPy object to/from PyObject

Example of converting an HPy handle to a PyObject *:

// src/_path_wrapper.cpp
static HPy Py_is_sorted(
        HPyContext *ctx,
        HPy self, 
+       HPy obj) {
-       PyObject *obj) {
    npy_intp size;
    bool result;

    PyArrayObject *array = (PyArrayObject *)PyArray_FromAny(
+       HPy_AsPyObject(ctx, obj), 
-       obj, 
        NULL, 1, 1, 0, NULL);
    ...
}

Example of converting a PyObject * to an HPy handle:

// src/ft2font_wrapper.cpp
static HPy convert_xys_to_array(HPyContext *ctx, std::vector<double> &xys)
{
    npy_intp dims[] = {(npy_intp)xys.size() / 2, 2 };
    if (dims[0] > 0) {
+       return HPy_FromPyObject(ctx, PyArray_SimpleNewFromData(2, dims, NPY_DOUBLE, &xys[0]));
-       return PyArray_SimpleNewFromData(2, dims, NPY_DOUBLE, &xys[0]);
    } else {
+       return HPy_FromPyObject(ctx, PyArray_SimpleNew(2, dims, NPY_DOUBLE));
-       return PyArray_SimpleNew(2, dims, NPY_DOUBLE);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment