C++ Python import class; call methods -


i using python 2.7. not clear me how embed python inside c++ found here: http://docs.python.org/2.7/extending/embedding.html.

i have simple python example here in file named test.py:

class math:     #def __init__(self):     def add(self, num1, num2):         return num1 + num2      def subtract(self, num1, num2):         return num1 - num2 

from python, this:

>>> test import math >>> m = math() >>> = m.add(1, 2) >>> s = m.subtract(1, 2) 

i have beginning of c++ code this:

pyobject *pname, *pmodule; py_initialize(); pname = pystring_fromstring("test"); pmodule = pyimport_import(pname); 

that seems work fine. but, seems equivalent of doing in python:

import test 

how import python class math?

thanks

here's quick n' dirty example in c equivalent of...

>>> import mymath >>> m = mymath.math() >>> print '1 + 2 = %d' % m.add(1, 2) 

note i've renamed module test mymath because there's module called test in standard python library.

#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 major amount of work python/c api between py_initialize , py_finalize, you'll have watch reference counts, , use py_incref , py_decref when appropriate.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

keyboard - C++ GetAsyncKeyState alternative -

android - java.net.UnknownHostException(Unable to resolve host “URL”: No address associated with hostname) -