"Cython" tutorial to make Python explosive: When a function on the C ++ side has an overload.

Overview

I want to make the code written in C ++ a library that can be called in Python. However, there was a big wall called Cython.

This is "Cython" tutorial to make Python explosive: How to parse Enum class defined in C ++ code to Python Enum. This is a continuation of.

The code is listed in "github here", so please take a look.

Last time, I explained how to pass the Enum class declared in C ++ to the Enum class on the Python side when converting a library written in C ++ to Cython so that it can be used from Python.

This time, it will be the explanation of Cythonization when the function on the C ++ side is overloaded (when the configuration has the same function name but different arguments).

Situation explanation

Create the following function on the C ++ side of the library you have written so far. Here, the print_vector function is a function that can take `vector <int>` and `vector <double>` as arguments, and in such a case, the function Is said to be overloaded.

cpp_library/TestClass1.h



class TestClass1{
    private:
        TestClass2 property_test_class2;
        EnumForTestClass1 group;

    public:
        //~abridgement
        static void print_vector(vector<int> x);
        static void print_vector(vector<double> x);

The contents are just a function that prints the contents of the vector as shown below.

cpp_library/TestClass1.cpp


void TestClass1::print_vector(vector<int> x){
    for(int i=0; i<x.size(); i++){
        cout << x[i] << " ";
    }
    cout << endl;

}

void TestClass1::print_vector(vector<double> x){
    for(int i=0; i<x.size(); i++){
        cout << x[i] << " ";
    }
    cout << endl;

}

Cythonization

Consider calling this print_vector function from Cython as in the example.

cython/my_library.pxd


cdef extern from "../cpp_library/TestClass1.h" namespace "my_library":
    cdef cppclass TestClass1:
        #~abridgement
        void print_vector(vector[int] x)
        void print_vector(vector[double] x)    

cython/test_class1.pxd


cdef extern from "../cpp_library/TestClass1.h" namespace "my_library":
    cdef cppclass TestClass1:
        #~abridgement
        void print_vector(vector[int] x)
        void print_vector(vector[double] x)    

Here, we will implement the contents in `` `cython / test_class1.pyx```.

cython/test_class1.pyx


    @staticmethod
    def print_vector(list x):
        cdef TestClass1 testclass1
        return testclass1.print_vector(x)

When I try to run `python setup.py install` as

Error compiling Cython file:
------------------------------------------------------------
...
        return testclass1.test_vector_int_ref(x,y) 

    @staticmethod
    def print_vector(list x):
        cdef TestClass1 testclass1
        return testclass1.print_vector(x)
                                     ^
------------------------------------------------------------

cython/test_class1.pyx:51:38: no suitable method found

I get an error and get angry. .. It's natural when you think about it, but because the `` `print_vector``` function on the C ++ side is overloaded, You don't know which function you're referring to. To solve this, you need to cast and specify which function you are calling.

So, rewrite `cython / test_class1.pyx` as follows.

cython/test_class1.pyx


    @staticmethod
    def print_vector(list x):
        cdef TestClass1 testclass1
        
        if isinstance(x[0], int):
            return testclass1.print_vector(<vector[int]>x)
        elif isinstance(x[0], float):
            return testclass1.print_vector(<vector[double]>x)
        else:
            raise Exception('TypeError')

This is done by first specifying the argument x as `` `list``` and then Which function on the C ++ side is called is specified by the type of its contents.

If you actually write it like this, you can build it with `python setup.py install`,

test.py


import my_library as myl

if __name__ == "__main__":

    cl1 = myl.test()
    x = [1,2,3]
    y = [1.1, 2.2, 3.3]
    cl1.print_vector(x)
    cl1.print_vector(y)

When you run and test,

(myenv) root@e96f489c2395:/from_local/cython_practice# python test.py 
1 2 3 
1.1 2.2 3.3 

You can see that the function on the C ++ side can be called successfully.

Summary

This time, I explained Cythonization when the function on the C ++ side is overloaded (when the configuration has the same function name but different arguments).

I think it's almost covered, and what else do you often write in C ++? I haven't decided what to write next, so I'll write the next one as soon as the material is decided.

This time around.

end.

Recommended Posts

"Cython" tutorial to make Python explosive: When a function on the C ++ side has an overload.
"Cython" tutorial to make Python explosive: Handling when a function on the C ++ side is passed by reference.
"Cython" tutorial to make Python explosive: Pass the C ++ class object to the class object on the Python side. Part 2
"Cython" tutorial to make Python explosive: When C ++ code depends on the library. Preparation
"Cython" tutorial to make Python explosive: When C ++ code depends on the library. Write setup.py.
"Cython" tutorial to make Python explosive: When C ++ code depends on the library. First of all, CMake.
"Cython" tutorial to make Python explosive: How to parse an Enum class defined in C ++ code into a Python Enum.
"Cython" Tutorial to Make Python Explosive: Basic Configuration
Make a breakpoint on the c layer with python
[Python] Make the function a lambda function
Check the argument type annotation when executing a function in Python and make an error
[Python] I want to know the variables in the function when an error occurs!
[Python] Smasher tried to make the video loading process a function using a generator
How to deal with "^ [[A ^ [[B ^ [[C ^ [[D"] when you press the arrow keys when executing python on mac
Try to make a Python module in C language
A convenient function memo to use when you want to enter the debugger if an error occurs when running a Python script.
Specifies the function to execute when the python program ends
[Python] Make sure the received function is a user-defined function
[Python] How to call a c function from python (ctypes)
[C / C ++] Pass the value calculated in C / C ++ to a python function to execute the process, and use that value in C / C ++.
[python] A note when trying to use numpy with Cython
How to make a Python package (written for an intern)
When you want to hit a UNIX command on Python
[Python] I tried to make a simple program that works on the command line using argparse.
About the error I encountered when trying to use Adafruit_DHT from Python on a Raspberry Pi
How to make a string into an array or an array into a string in Python
[Introduction to Python] How to split a character string with the split function
A game to go on an adventure in python interactive mode
[Python3] Define a decorator to measure the execution time of a function
[Python] Explains how to use the format function with an example
The road to installing Python and Flask on an offline PC
[Python] A simple function to find the center coordinates of a circle
I tried to make an image similarity function with Python + OpenCV
I tried to make a serial communication single function module that controls the servo motor on the Petit Robo board in C language
Extension of Python by C or C ++ (when there are multiple arguments, when passing a list from the Python side)
How to make a recursive function
I want to pass an argument to a python function and execute it from PHP on a web server
[Python Tutorial] An Easy Introduction to Python
Things to watch out for when creating a Python environment on a Mac
[Python] Explains how to use the range function with a concrete example
Python Note: When you want to know the attributes of an object
[Python] Create a linebot to write a name and age on an image
The eval () function that calculates a string as an expression in python
[Introduction to Python] How to write a character string with the format function
[C language] How to use the crypt function on Linux [Password hashing]
Python: I want to measure the processing time of a function neatly
I made a function to see the movement of a two-dimensional array (Python)
Precautions when pickling a function in python
[Python] A progress bar on the terminal
An introduction to Python for C programmers
[2015/11/19] How to register a service locally using the python SDK on naoqi os
Make a Python program a daemon and run it automatically when the OS starts
In the Chainer tutorial, I get an error when importing a package. (mock)
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
I stumbled on the character code when converting CSV to JSON in Python
Feel free to turn Python using the library into an AWS Lambda function
Set an upper limit on the number of recursive function iterations in Python
[Python] Solution to the problem that elements are linked when copying a list
[Python] I tried to get the type name as a string from the type function
On Linux (Ubuntu), tune the Trackpad and set the function to a three-finger swipe