Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2010
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. #include <Python.h>
  2. #include <time.h>
  3.  
  4. static PyObject *
  5. node_stuff(PyObject *self, PyObject *args)
  6. {
  7.     return Py_BuildValue("s", "Hello World");
  8. }
  9.  
  10. static PyMethodDef NodeMethods[] = {
  11.     {"stuff", node_stuff, METH_VARARGS, "Just do stupid stuff."},
  12.     {NULL, NULL, 0, NULL}
  13. };
  14.  
  15. static PyModuleDef NodeModule = {
  16.     PyModuleDef_HEAD_INIT, "node", NULL, -1, NodeMethods,
  17.     NULL, NULL, NULL, NULL
  18. };
  19.  
  20. static PyObject *
  21. PyInit_node(void)
  22. {
  23.     PyModule_Create(&NodeModule);
  24. }
  25.  
  26. int main(int argc, char *argv[])
  27. {
  28.     PyObject *pModuleName, *pTestModule, *pTestFunc, *pTestResult, *pTestArgs;
  29.    
  30.     PyImport_AppendInittab("node", &PyInit_node);
  31.     Py_Initialize();
  32.  
  33.     PyRun_SimpleString("import sys\nsys.path.append(\"\")");
  34.    
  35.     PyRun_SimpleString("import sys\nprint(sys.path)");
  36.    
  37.     pModuleName = PyUnicode_FromString("stuff");
  38.     pTestModule = PyImport_Import(pModuleName);
  39.     Py_DECREF(pModuleName);
  40.  
  41.     if (pTestModule != NULL)
  42.     {
  43.         PyObject_Print(PyObject_Dir(pTestModule), stdout, 0);
  44.         PyObject_Print(PyObject_GetAttrString(pTestModule, "__name__"), stdout, 0);
  45.         printf("\n");
  46.         pTestFunc = PyObject_GetAttrString(pTestModule, "do_stuff");
  47.         if (pTestFunc && PyCallable_Check(pTestFunc))
  48.         {
  49.             pTestArgs = PyTuple_New(0);
  50.             pTestResult = PyObject_CallObject(pTestFunc, pTestArgs);
  51.             Py_DECREF(pTestArgs);
  52.             if (pTestResult != NULL)
  53.             {
  54.                 printf("Result of call: %ld\n", PyLong_AsLong(pTestResult));
  55.                 Py_DECREF(pTestResult);
  56.             }
  57.             else
  58.             {
  59.                 Py_DECREF(pTestFunc);
  60.                 Py_DECREF(pTestModule);
  61.  
  62.                 PyErr_Print();
  63.  
  64.                 fprintf(stderr, "Call failed!\n");
  65.                 return 1;
  66.             }
  67.         }
  68.         else
  69.         {
  70.             if (PyErr_Occurred())
  71.                 PyErr_Print();
  72.             fprintf(stderr, "Could not find function.\n");
  73.         }
  74.         Py_XDECREF(pTestFunc);
  75.         Py_DECREF(pTestModule);
  76.     }
  77.     else
  78.     {
  79.         PyErr_Print();
  80.         fprintf(stderr, "Failed to load module.\n");
  81.         return 1;
  82.     }
  83.  
  84.     Py_Finalize();
  85.  
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement