
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use Python Object in C++
Here is an example in which a simple Python object is wrapped and embedded. We are using .c for this, c++ has similar steps −
class PyClass(object): def __init__(self): self.data = [] def add(self, val): self.data.append(val) def __str__(self): return "Data: " + str(self.data) cdef public object createPyClass(): return PyClass() cdef public void addData(object p, int val): p.add(val) cdef public char* printCls(object p): return bytes(str(p), encoding = 'utf-8')
We compile with cython pycls.pyx (use --cplus for c++) to generate a .c and .h file containing the source and the function declarations respectively. We now create a main.c file that starts up Python and we are ready to call these functions −
#include "Python.h" // Python.h always gets included first. #include "pycls.h" // Include your header file. int main(int argc, char *argv[]){ Py_Initialize(); // initialize Python PyInit_pycls(); // initialize module (initpycls(); in Py2) PyObject *obj = createPyClass(); for(int i=0; i<10; i++){ addData(obj, i); } printf("%s\n", printCls(obj)); Py_Finalize(); return 0; }
Compiling this with the proper flags (which you can obtain from python3.5-config of python-config [Py2]) −
gcc pycls.c main.c -L$(python3.5-config --cflags) -I$(python3.5-config --ldflags) -std=c99
will create our executable which interacts with our object −
./a.out Data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
All this was done by using Cython along with the public keyword that generates the .h header file. We could alternatively just compile a python module with Cython and create the header/handle the additional boilerplate ourself.