/* * Copyright (C) 2020 Weber Yann * * This file is part of pyrpn. * * pyrpn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * pyrpn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with pyrpn. If not, see . */ #include "python_pyrpn.h" /**@file python_pyrpn.c * @brief Python module & type definition * @ingroup python_ext * * This file contains pyrpn Python module definition */ PyMethodDef rpnmodule_methods[] = { {"get_ops", (PyCFunction)pyrpn_ops, METH_NOARGS, "Returns a valid operands dict"}, {"random_expr", (PyCFunction)pyrpn_random, METH_VARARGS | METH_KEYWORDS, "Return a random RPN expression"}, {NULL} // Sentinel }; PyModuleDef rpnmodule = { PyModuleDef_HEAD_INIT, "pyrpn", "Python librarie for RPN evaluation", -1, // module size rpnmodule_methods, NULL, // m_slots NULL, // m_traverse NULL, // m_clear NULL // m_free }; PyMODINIT_FUNC PyInit_pyrpn(void) { PyObject *mod; // init module & globals mod = PyModule_Create(&rpnmodule); if(mod == NULL) { return NULL; } // Init RPNExpr type if(PyType_Ready(&RPNExprType) < 0) { return NULL; } // Add type to module Py_INCREF(&RPNExprType); if(PyModule_AddObject(mod, "RPNExpr", (PyObject*)&RPNExprType) < 0) { Py_DECREF(&RPNExprType); Py_DECREF(mod); return NULL; } return mod; } PyObject* pyrpn_ops(PyObject* mod, PyObject* noargs) { PyObject *ret, *value; const rpn_op_t *op; size_t i; ret = PyDict_New(); if(!ret) { return ret; } foreach_rpn_ops(i) { op = &rpn_ops[i]; value = Py_BuildValue("C", op->chr); if(PyDict_SetItemString(ret, op->str, value)) { Py_DECREF(value); Py_DECREF(ret); return NULL; } Py_DECREF(value); } return ret; } PyObject* pyrpn_random(PyObject *mod, PyObject *args, PyObject *kwds) { long long int args_count, expr_sz; char *expr, err_str[128]; PyObject *res; char *names[] = {"args_count", "token_count", NULL}; expr_sz = 10; if(!PyArg_ParseTupleAndKeywords(args, kwds, "L|L:pyrpn.random_expr", names, &args_count, &expr_sz)) { return NULL; } expr = rpn_random(expr_sz, args_count); if(!expr) { snprintf(err_str, 128, "Error generating random expression : %s", strerror(errno)); PyErr_SetString(PyExc_RuntimeError, err_str); return NULL; } res = Py_BuildValue("s", expr); //free(expr); return res; }