Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Python.h>
- // source: https://stackoverflow.com/questions/8001923/python-extension-module-with-variable-number-of-arguments
- // source: https://codedamn.com/news/python/implementing-custom-python-c-extensions-step-by-step-guide
- static PyObject* compute_linear_index(PyObject* self, PyObject* args) {
- Py_ssize_t order = PyTuple_Size(args) / 2;
- Py_ssize_t i;
- unsigned int *dimensions;
- unsigned int *index;
- long p = 1;
- long final = 0;
- dimensions = malloc(order*sizeof(unsigned int));
- for(i = 0; i < order; i++) {
- dimensions[i] = PyLong_AsUnsignedLong(PyTuple_GetItem(args, i));
- }
- index = malloc(order*sizeof(unsigned int));
- for(i = 0; i < order; i++) {
- index[i] = PyLong_AsUnsignedLong(PyTuple_GetItem(args, i+order));
- };
- for(i = 0; i < order; i++) {
- final += index[order-i-1]*p;
- p *= dimensions[order-i-1];
- }
- free(dimensions);
- free(index);
- return PyLong_FromLong(final);
- }
- static PyMethodDef TensorMethods[] = {
- {"compute_linear_index", compute_linear_index, METH_VARARGS, "Compute linear index."},
- {NULL, NULL, 0, NULL} /* Sentinel */
- };
- static struct PyModuleDef tensor_module = {
- PyModuleDef_HEAD_INIT,
- "tensor", /* name of module */
- 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. */
- TensorMethods
- };
- PyMODINIT_FUNC PyInit_tensor(void) {
- return PyModule_Create(&tensor_module);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement