Advertisement
cirossmonteiro

python c extension

Feb 27th, 2025 (edited)
274
0
29 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.57 KB | None | 0 0
  1. #include <Python.h>
  2.  
  3. // source: https://stackoverflow.com/questions/8001923/python-extension-module-with-variable-number-of-arguments
  4. // source: https://codedamn.com/news/python/implementing-custom-python-c-extensions-step-by-step-guide
  5.  
  6. static PyObject* compute_linear_index(PyObject* self, PyObject* args) {
  7.     Py_ssize_t order = PyTuple_Size(args) / 2;
  8.     Py_ssize_t i;
  9.     unsigned int *dimensions;
  10.     unsigned int *index;
  11.     long p = 1;
  12.     long final = 0;
  13.    
  14.     dimensions = malloc(order*sizeof(unsigned int));
  15.     for(i = 0; i < order; i++) {
  16.         dimensions[i] = PyLong_AsUnsignedLong(PyTuple_GetItem(args, i));
  17.     }
  18.  
  19.     index = malloc(order*sizeof(unsigned int));
  20.     for(i = 0; i < order; i++) {
  21.         index[i] = PyLong_AsUnsignedLong(PyTuple_GetItem(args, i+order));
  22.     };
  23.  
  24.     for(i = 0; i < order; i++) {
  25.         final += index[order-i-1]*p;
  26.         p *= dimensions[order-i-1];
  27.     }
  28.  
  29.     free(dimensions);
  30.     free(index);
  31.  
  32.     return PyLong_FromLong(final);
  33. }
  34.  
  35. static PyMethodDef TensorMethods[] = {
  36.     {"compute_linear_index", compute_linear_index, METH_VARARGS, "Compute linear index."},
  37.     {NULL, NULL, 0, NULL} /* Sentinel */
  38. };
  39.  
  40. static struct PyModuleDef tensor_module = {
  41.     PyModuleDef_HEAD_INIT,
  42.     "tensor", /* name of module */
  43.     NULL,           /* module documentation, may be NULL */
  44.     -1,             /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
  45.     TensorMethods
  46. };
  47.  
  48. PyMODINIT_FUNC PyInit_tensor(void) {
  49.     return PyModule_Create(&tensor_module);
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement