[C++/python] How to use a Python class in C + +? (Use python-defined class in C + +)

Source: Internet
Author: User

Recently in the OPENCV-based license plate recognition, which requires some code for deep learning (python), the development language at the outset chose Python (the source of the scourge).

Although the speed of Python is not too slow now, but you must use Python to manipulate the image, when implementing some algorithms, efficiency becomes very important. Unfortunately, Python in most implementations of the algorithm, because its loop operation is too slow, resulting in the implementation of the algorithm is very low.

So now I'm going to convert a class (classifier) in deep learning into C + +, before this process, I need to do some test projects, my main reference is: C + + calls Python (3).

The development environment is VS2012, WIN7 64.

All of the code is released at the end, which is explained gradually.

First we need to import the appropriate header file: Python.h, which is located in the Include directory of your Python installation directory. (2.6, 2.7 version measured through)

Using VS, you can set the project properties as follows:

    1. debugging, XXX properties (last column), VC + + directory, right-side Library Directory
    2. Increase C:\Python27\libs, specific path individual may be different.

This completes the most basic configuration, and below we begin to import the. py file and use it.

The. py file we use is very simple and the code is as follows:

1 #!/usr/bin/python2 #Filename:testpy.py3 classPerson :4     defSayhi (self):5         Print 'Hi'6 classSecond:7     defInvoke (self,obj):8 Obj.sayhi ()9 defSayhi (name):Ten     Print 'Hi', name;

Note: All of the following import methods do not error when importing fails and only return null pointers.

The first step is to import the. py file:

    1. Using pyobject* Pmodule to store the imported. py file module, the method called is pyimport_importmodule (path): pyobject* pmodule = Pyimport_ Importmodule ("testpy");
    2. Use pyobject* Pdict to store the method dictionary in the import module, which is called pymodule_getdict (module): pyobject* pdict = pymodule_getdict ( Pmodule);

This completes the import of the. py file.

The second step is to import the methods or classes in the imported module:

    1. Gets the method that is called by pydict_getitemstring (dict, MethodName): pyobject* pfunhi = Pydict_getitemstring (Pdict, "Sayhi");  
    2. Get the class, call the method above, notice that the red body part of the string corresponds to the class/method name in the. py file: pyobject* pclasssecond = pydict_getitemstring (pdict, "Second" );

The third step is to use the imported method or class:

  1. Using the method, call pyobject_callfunction (PFunc, "s", args) to: pyobject_callfunction (Pfunhi, "s ", "LHB");
  2. Using the class construct object, call pyinstance_new (pClass, NULL, NULL) to: pyobject* Pinstancesecond = pyinstance_new ( Pclasssecond, NULL, NULL); , note that the Pclasssecond is the second step. class pointer obtained in 2
  3. Using the method of the class object, call Pyobject_callmethod (pinstance, MethodName, "O", args) : Pyobject_callmethod ( Pinstancesecond, "invoke", "O", Pinstanceperson);

Finally, do not forget to destroy these objects: py_decref (pointer);

The following is the C + + implementation code, the code is from my reference blog, slightly modified.

1 /*2 * Test.cpp3 * Created on:2010-8-124 * Author:lihaibo5  */6#include <C:/Python27/include/Python.h>7#include <iostream>8#include <string>9 Ten intMainvoid) { OnePy_initialize ();//start a virtual machine A     if(!py_isinitialized ()) -         return-1; -     //Import Module thepyobject* Pmodule = Pyimport_importmodule ("testpy"); -     if(!pmodule) { -printf"Cant Open python file!/n"); -         return-1; +     } -     //Dictionary List of modules +pyobject* pdict =pymodule_getdict (pmodule); A     if(!pdict) { atprintf"Cant Find dictionary./n"); -         return-1; -     } -     //Demo function Call -pyobject* Pfunhi = pydict_getitemstring (Pdict,"Sayhi"); -Pyobject_callfunction (Pfunhi,"s","LHB"); in Py_decref (PFUNHI); -     //demonstrates constructing a Python object and calling the class method to     //get Second Class +pyobject* Pclasssecond = pydict_getitemstring (Pdict,"Second"); -     if(!Pclasssecond) { theprintf"Cant Find Second class./n"); *         return-1; $     }Panax Notoginseng     //Get Person class -pyobject* Pclassperson = pydict_getitemstring (Pdict," Person"); the     if(!Pclassperson) { +printf"Cant Find Person class./n"); A         return-1; the     } +     //example of constructing second -pyobject* Pinstancesecond =pyinstance_new (pclasssecond, NULL, NULL); $     if(!Pinstancesecond) { $printf"Cant Create second instance./n"); -         return-1; -     } the     //construct an instance of person -pyobject* Pinstanceperson =pyinstance_new (Pclassperson, NULL, NULL);Wuyi     if(!Pinstanceperson) { theprintf"Cant Find Person instance./n"); -         return-1; Wu     } -     //The invoke method of passing the person instance into the second AboutPyobject_callmethod (Pinstancesecond,"Invoke","O", Pinstanceperson); $     //Release - Py_decref (pinstancesecond); - Py_decref (Pinstanceperson); - Py_decref (pclasssecond); A Py_decref (Pclassperson); + Py_decref (pmodule); thePy_finalize ();//shutting down a virtual machine -     return 0; $}

[C++/python] How to use a Python class in C + +? (Use python-defined class in C + +)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.