C ++ uses ffpython to embed and extend python

Source: Internet
Author: User
Tags what interface

Abstract:

Python script technology is often used in Server programming. Python is one of the most popular scripts, and python has well-defined c api interfaces. It also has a wide range of documents, which are very suitable for combination with C ++. Generally, the C ++ encapsulation mechanism is used, and the python script is used to implement the policy or control. The combination of python and C ++ has the following advantages:

  • L The main system is implemented using C ++ to ensure system efficiency.
  • L The control part uses python to increase development efficiency. python's memory garbage collection and rich class libraries have benefited C ++ developers a lot.
  • L The Python script can be reloaded at runtime, and the control part can be hot updated without stopping services.

C ++ is very different from the python programming paradigm. When using python c api to call python, some special mechanisms in python will bring a lot of confusion to C ++ developers. Pay attention to the following points when using python C APIs:

  • L Python uses reference count to manage memory. when calling the python c api, you must carefully confirm whether the returned value is a borrowed reference or a new reference. Otherwise, memory leakage occurs, and the program crashes.
  • L The data structure in Python is very different from that in C ++. Python commonly uses tuple, list, And dict. C ++ is commonly used for vector, list, and map, and c ++ is strongly typed. When c ++ interacts with python, the C ++ layer wants to operate python data structures as conveniently as c ++ STL, while in the python script layer, it is also expected that the input parameters or returned values of c ++ are native python data.
  • L commonly used pointer passing objects in C ++. When embedding python, the c ++ object must be passed to python.

Ffpython is a class library designed to facilitate C ++ embedded in python development. On the one hand, it can easily integrate python into the C ++ system, on the other hand, C ++ objects or interfaces can be easily used by python. In short, ffpython simplifies the interaction between c ++ and python.

Embed python

The simplest way to use python is to use the python script as a configuration, such as getting a string variable in the script. The Python script file is imported as a module by the python virtual machine, which is similar to the module in the python standard library. Ffpython encapsulates the operations to obtain the variables in the python module.

printf(, ffpython.get_global_var<>(, ).c_str());

 

The above code gets the sys version variable value in the python standard library. ffpython automatically adapts the python str type to the string type of c ++ through the template function. Get_global_var is the interface for getting variables, corresponding to the excuse for setting variables get_global_var:

ffpython.get_global_var(, , , ffpython.get_global_var<>(, ).c_str());

 

Calling python functions is a very common operation to embed python. ffpython provides the call interface to call functions of modules in python:

printf(, ffpython.call<>(, ).c_str());

 

The above code calls the asctime method of the time module. We can also use the call interface to call our own functions:

 a1 = ;  a2 = ;  a3 = <>(, , a1, a2, a3);

 

Call is defined as a template function. The input parameters are automatically adapted to the corresponding python type. The corresponding python functions are:

( 0

 

The above python function accepts three parameters. c ++ imports three standard parameters. In fact, the call interface supports a maximum of nine generic parameters. Common stl parameters are supported:

 

 test_stl(ffpython_t&<> a1;a1.push_back();a1.push_back(<> a2; a2.push_back();a2.push_back(<list<> ><>(, 

 

The python function is called as follows:

( True

 

Not only is STL generic supported, but the nested structure similar to vector <list <string> is supported. Both vector and list are converted to the list structure of python, map is converted to the dict structure.

To call the call interface, you must specify the type of returned values. You can use void to ignore the returned values. In addition to standard types, the stl interface can also be used, in python, tuple and list can be converted to vector and list, while dict can be converted to map. Note that if the type does not match, the call function will throw an exception. You can catch a standard exception. The string returned by what interface contains the exception traceback information for troubleshooting. Example:

    (exception&

 

Python Extension

Ffpython can register static functions to python. The global C-style static functions and static functions defined in the class can be registered to python, for example:

  print_val( a1,  a2,  & a3,  vector<>&  list<><> ret;ret.push_back(&print_val, &ops_t::return_stl, <>(, 

 

The above code registers two interfaces for python, and then calls test_reg_function in the fftest file to test the two interfaces. Define the test code in fftest. py:

123, 45.6 , , [3.14=(, ret)

 

Although the two interfaces are simple, they indicate that the interfaces registered with ffpython support multiple parameters. The parameter types can be standard C ++ or STL generics. The same is true for the type of the returned value.

It is also easy to use ffpython to register C ++ objects. ffpython supports registering c ++ class constructors, member variables, and member methods to python. The sample code is as follows:

 

 ~ get_value()  {  set_value( v_) { m_value = test_stl(map<, list<> >& dumy_t: ~ foo_t* obj_test(dumy_t* test_register_base_class(ffpython_t&<foo_t, PYCTOR()>(&foo_t::get_value, &foo_t::set_value, &foo_t::test_stl, &foo_t::m_value, <dumy_t, PYCTOR()>(, , &dumy_t::dump, <>(, 

 

After the c ++ type is registered in python, it is as convenient as the built-in type in python. Note that, if a c ++ object is dynamically created in python, it is managed by the python GC, so when the variable is not referenced, the destructor of the c ++ object is called. The script code tested in fftest. py is as follows:

= ext2.foo_t(20130426(778899(: [11,22,33(, foo)

 

Similar to the principles stated by the front edge, the C ++ standard built-in type and STL generic type are supported. When this python function is returned, the foo_t destructor will be called.

Dumy_t is a subclass of foo_t. Ffpython can easily represent two types of relationships. If the base class has already defined interfaces, the subclass does not need to be defined repeatedly. For example, to register a subclass:

ffpython.reg_class<dumy_t, PYCTOR()>(, , &dumy_t::dump,  test_register_inherit_class(ffpython_t&<>(, 

 

You only need to register the unique interfaces of the class separately. Other interfaces are automatically inherited from the foo_t base class, and the corresponding python test script code is:

= ext2.dumy_t(20130426(778899(: [11,22,33(, dumy)

 

One of the most useful features of Ffpython is that objects created by c ++ can be passed to python, and python is used just like normal python objects, in addition, the c ++ object created by python can also be passed to c ++. Simple sample code:

ffpython.reg(obj_test,  test_cpp_obj_to_py(ffpython_t&<>(, , & test_cpp_obj_py_obj(ffpython_t&* p = ffpython.call<foo_t*>(, , &

 

The test script code in fftest. py is as follows:

(778899(: [11,22,33((778899(: [11,22,33( dumy

 

Summary:
  • L Ffpython supports c ++ to call python functions to obtain and set variables in the module
  • L The Ffpython call interface supports a maximum of nine generic parameters. The supported types include c ++ built-in types and STL generic types. And the pointer type of the registered c ++ class. The same is true for type constraints of return values. The vector and list in c ++ STL correspond to the tuple and list in python, and the map type corresponds to dict.
  • L Ffpython supports registering c ++ static functions to python.
  • L Ffpython supports registration of c ++ classes and inheritance. In Python, operating c ++ objects is like operating native python objects.
  • L after the c ++ class registered by Ffpython is created in python, the python GC is responsible for memory collection.
  • L The Ffpython class library has only one file and does not rely on other third-party libraries. It is very easy to integrate into the project. In addition, ffpython complies with open-source protocols.
  • L Ffpython uses the c ++ template technology to encapsulate the details of the use of python C APIs, keeping them exquisite and concise, and the efficiency is almost the same as the code written by the python c api. The implementation of Ffpython can be used as an example of a very good python c api.
  • L Github Project address: https://github.com/fanchy/ffpython

 

Related Article

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.