1. The function of so file

Python is efficient, but not as efficient as C/C++; In addition, sometimes we want to protect some key code, we can compile this code into C/C++ so library, and then use Python to call, to achieve the purpose of source protection

2. Package python files as so packages

  1. Install cython
pip install cython
Copy the code
  1. Create a new file to compile, hello.py and setup.py

Hello.py reads as follows:

def greet(str) :
    return "hello " + str
Copy the code

Setup.py reads as follows:

from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize(["hello.py"]))

Copy the code

Run the following package commands:

python setup.py build_ext
Copy the code

After the command is executed, the hello.c file is generated in the same directory as the build folder, where the compiled.so file is stored.

If you need to package multiple py files, modify the setup.py content:

from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize(["hello1.py", "hello2.py","hello3.py"]))
Copy the code

2.2 C++/ C package into so package method

Write a C++ file called add.cpp:

#include <iostream>
using namespace std;

extern "C"{

   double add(int x1, int x2){
		return x1+x2;
	}

   void print_msg(const char* s){ cout<<s; }}int main(a){
	int a = 1;
	int b =2 ;
	int c;
	c = add(a,b);
	return c;
}


Copy the code

Extern “C” is an extern “C” function that needs to be converted to C syntax. Since C++ functions can be overridden, using g++ will attach additional information to the function name, such as void print(int a); Compiling with g++ will generate print_int and the like, which will not be found when cdll.loadlibrary is used. Therefore, we need to have the compiler compile using the C method in order to achieve this goal.

Compile to library files:

g++ add.cpp -fpic -shared -o libadd.so
Copy the code

Call from a Python file:

# _*_ encoding : utf-8 _*_
import os
from ctypes import *

lib = cdll.LoadLibrary(os.getcwd() + "/libadd.so")
lib.add.restype = c_double

input_1 = 100
input_2 = 200
result1 = lib.add(input_1,input_2)
result2 = lib.main()

print(result1, result2)
lib.print_msg(b"This string will be printed\n")
Copy the code