Python Sutdy, To use python class in the c source code (Python embedding)

This post is that how to embed python file in C source code.
Most articles in internet is opposed concept, such as to embed C source code into python

"Extending" is called to embed C module into Python
"Embedding" is called  to embed Python module into C

This article is about embedding.
My final goal is that coding opencv in python and relase to C, C++ users by dll type.

This source cod is example how to use python class in the C.
You can know easily if you see the code carefully.

..
main.cpp
#include 

#ifdef _DEBUG           
#pragma comment(lib, "python27_d.lib")  //Now, this option does not run.
#else   
#pragma comment(lib, "python27.lib")   
#endif    



void main()
{
 PyObject *module, *request, *mP;
 float rVal;

 Py_Initialize();
 module = PyImport_ImportModule("emPy"); //.py file name
 if( module == NULL)
 {
  PyErr_Clear();
  printf("Unable to import embed module");
 }

 request = PyObject_CallMethod(module, "myPower", NULL); //class name
 if(request == NULL)
 {
  PyErr_Clear();
  printf("fail to call class");
 }

 mP = PyObject_CallMethod(request, "myPow","f",10.0); //member function name, input value

 if(mP == NULL)
 {
  PyErr_Clear();
  printf("fail to call function");
 }else{
  PyArg_Parse(mP,"f", &rVal);  //get value from class function of .py
  printf("%lf \n", rVal);
 }

 //clear
 if( module != NULL )
  Py_DECREF(module);
 else
  PyErr_Print();

 if( request != NULL )
  Py_DECREF(request);
 else
  PyErr_Print();
 
 if( mP != NULL )
  Py_DECREF(mP);
 else
  PyErr_Print();
 
 Py_Exit(0);
}
..



emPy.py
...
class myPower:
    def myPow(self, inA):
        print inA*inA
        return inA*inA

...

Environment setting
- emPy.py should be located same directory with main.cpp
- Path setting -> include -> "C:\Python27\include"
                           lib        -> "C:\Python27\libs"


Comments

Popular posts from this blog

(OpenCV Study) Background subtractor MOG, MOG2, GMG example source code (BackgroundSubtractorMOG, BackgroundSubtractorMOG2, BackgroundSubtractorGMG)

OpenCV Stitching example (Stitcher class, Panorama)

AMP dose run on my pc?, AMP(Accelerated Massive Parallelism)

Example source code of extract HOG feature from images, save descriptor values to xml file, using opencv (using HOGDescriptor )

Optical Flow sample source code using OpenCV

Real-time N camera stitching Class.

8 point algorithm (Matlab source code) / The method to get the Fundamental Matrix and the Essential matrix

OpenCV meanShiftFiltering example source code ( cpu: pyrMeanShiftFiltering, gpu:meanShiftFiltering, gpu:meanShiftSegmentation )

Image warping (using opencv findHomography, warpPerspective)

Video Stabilization example source code, (using cvFindHomography, cvWarpPerspective functions in openCV)