Here's a quick n 'dirty example in C that does the equivalent ...
>>> import mymath >>> m = mymath.math() >>> print '1 + 2 = %d' % m.add(1, 2)
Note that I renamed the module from test to mymath , because the Python standard library has a module called test .
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <python2.7/Python.h> int main() { setenv("PYTHONPATH", ".", 1); Py_Initialize(); PyObject* module = PyImport_ImportModule("mymath"); assert(module != NULL); PyObject* klass = PyObject_GetAttrString(module, "math"); assert(klass != NULL); PyObject* instance = PyInstance_New(klass, NULL, NULL); assert(instance != NULL); PyObject* result = PyObject_CallMethod(instance, "add", "(ii)", 1, 2); assert(result != NULL); printf("1 + 2 = %ld\n", PyInt_AsLong(result)); Py_Finalize(); return 0; }
... which outputs ...
$ gcc foo.c -lpython2.7 && ./a.out 1 + 2 = 3
However, if you are doing any great work with the Python / C API between Py_Initialize and Py_Finalize , you will need to keep track of the number of links and use Py_INCREF and Py_DECREF when necessary.
source share