nnabla icon indicating copy to clipboard operation
nnabla copied to clipboard

Can I use nbla::Array in a extenstion created by C Python API?

Open twmht opened this issue 5 months ago • 1 comments

Hi,

How to create nbla::Array in the c extension and return it to python side?

for example with numpy we can do

#include <Python.h>
#include <numpy/arrayobject.h>

static PyObject* create_numpy_array(PyObject* self, PyObject* args) {
    // Parse arguments if needed

    // Initialize Python and NumPy
    Py_Initialize();
    import_array();

    // Create a NumPy array
    npy_intp dims[2] = {3, 3};  // dimensions of the 2D array
    PyObject* myArray = PyArray_SimpleNew(2, dims, NPY_DOUBLE);

    // Access the array data
    double* data = (double*)PyArray_DATA(myArray);

    // Fill the array with some data
    for (npy_intp i = 0; i < dims[0]; ++i) {
        for (npy_intp j = 0; j < dims[1]; ++j) {
            data[i * dims[1] + j] = i + j;
        }
    }

    // Return the NumPy array
    return myArray;
}

static PyMethodDef methods[] = {
    {"create_numpy_array", create_numpy_array, METH_NOARGS, "Create and return a NumPy array"},
    {NULL, NULL, 0, NULL} // Sentinel
};

static struct PyModuleDef module = {
    PyModuleDef_HEAD_INIT,
    "my_module", // Module name
    NULL,        // Module documentation, may be NULL
    -1,          // Size of per-interpreter state of the module, or -1 if the module keeps state in global variables.
    methods
};

PyMODINIT_FUNC PyInit_my_module(void) {
    import_array();  // Must be called before PyModule_Create

    return PyModule_Create(&module);
}

but nbla::Array python interface is created by Cython, I am not sure how to use that in my c extension.

Any idea?

twmht avatar Feb 02 '24 05:02 twmht