C ++ Python import class; calling methods

I am using Python 2.7. I don’t understand how to embed Python inside C ++, as shown here: http://docs.python.org/2.7/extending/embedding.html .

I have a simple python example here in a file called 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, I would do something like this:

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

I have the beginning of some C ++ code:

 PyObject *pName, *pModule; Py_Initialize(); pName = PyString_FromString("test"); pModule = PyImport_Import(pName); 

Everything seems to be working fine. But it seems like this is equivalent to doing this in Python:

 import test 

How to import Python class math?

thanks

+4
source share
2 answers

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.

+9
source

You cannot import a class, but you can import a file or library (how is this true for most languages?) - this is exactly what you did here in the case of test.py.

0
source

Source: https://habr.com/ru/post/1480728/


All Articles