Guest User

Untitled

a guest
Feb 18th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. #include <Python.h>
  2.  
  3. static PyObject* test_square(PyObject *self, PyObject *args) {
  4. const int* i;
  5.  
  6. if (!PyArg_ParseTuple(args, "l", &i))
  7. return NULL;
  8.  
  9. return PyLong_FromLong(*i**i);
  10. }
  11. /*
  12. For void functions
  13. Py_INCREF(Py_None);
  14. return Py_None;
  15. */
  16.  
  17. static PyMethodDef TestMethods[] = {
  18. {"test_square", test_square, METH_VARARGS, "Square a number."},
  19. {NULL, NULL, 0, NULL} /* Sentinel */
  20. };
  21.  
  22. static struct PyModuleDef testmodule = {
  23. PyModuleDef_HEAD_INIT,
  24. "test", /* name of module */
  25. NULL, /* originally test_doc, module documentation, may be NULL */
  26. -1, /* size of per-interpreter state of the module,
  27. or -1 if the module keeps state in global variables. */
  28. TestMethods
  29. };
  30.  
  31. PyMODINIT_FUNC PyInit_test(void)
  32. {
  33. PyObject* module;
  34.  
  35. module = PyModule_Create(&testmodule);
  36. if (module == NULL)
  37. return NULL;
  38.  
  39. TestError = PyErr_NewException("test error thrown", NULL, NULL);
  40. Py_INCREF(TestError);
  41. PyModule_AddObject(module, "test error added", TestError);
  42. return module;
  43.  
  44. return PyModule_Create(&testmodule);
  45. }
  46.  
  47. from distutils.core import setup, Extension
  48.  
  49. # the c++ extension module
  50. test_module_py = Extension("assignment1", sources=["assignment1.c"])
  51.  
  52. setup(name='PackageName',
  53. version='1.0',
  54. description='This is a demo package',
  55. ext_modules=[test_module_py])
  56.  
  57. #include <Python.h>
  58. #include "sum.h"
  59.  
  60. static PyObject* mod_sum(PyObject *self, PyObject *args)
  61. {
  62. int a;
  63. int b;
  64. int s;
  65. if (!PyArg_ParseTuple(args, "ii", &a, &b))
  66. return NULL;
  67. s = sum(a, b);
  68. return Py_BuildValue("i", s);
  69. }
  70.  
  71. static PyMethodDef ModMethods[] = {
  72. { "sum", mod_sum, METH_VARARGS, "Description.." },
  73. { NULL,NULL,0,NULL }
  74. };
  75.  
  76. PyMODINIT_FUNC initmod(void)
  77. {
  78. PyObject *m;
  79. m = Py_InitModule("module", ModMethods);
  80. if (m == NULL)
  81. return;
  82. }
  83.  
  84. int sum(int a, int b) {
  85. return a + b;
  86. }
  87.  
  88. import assignment1
  89.  
  90. s = assignment1.sum(1, 5)
  91.  
  92. print(s)
Add Comment
Please, Sign In to add comment