Using pybind11 to develop extension modules for python

Using pybind11 to develop extension modules for python

For example, you can use pybind11 to encapsulate a C++ class into Python. Most of the bottom layer of Python is encapsulated in C++, which can take advantage of the computing performance of C++ and the convenience of Python.

How to define a module with pybind11? Let’s briefly explain it with the code below.

//表示module的名称叫yolo,到时候python中import的包的名字也是这个
//m其实是一个模块的实例对象,可通过查看源码中PYBIND11_MODULE的定义知晓
//PYBIND11_MODULE就是一个宏
PYBIND11_MODULE(yolo, m){
    
    
//m.def表示定义了一个函数
    m.def(
		"compileTRT", compileTRT,//第一个参数表示定义的函数的名称,第二个参数表示关联的是哪个实际的c++函数
		//py::arg用法是告诉python调用层能看到定义的函数中的参数名称是什么
		//后面的= 表示默认的参数,这就相当于我们在python中定义一个函数指定好默认值是一样的
		py::arg("max_batch_size"),
		py::arg("source"),
		py::arg("output"),
		py::arg("fp16")                         = false,
		py::arg("device_id")                    = 0,
		py::arg("max_workspace_size")           = 1ul << 28
	);
}

refer:
# and ## in C++ : Commonly used to define macros
in python and call C++. Introduction to pybind11 : .pyd (Windows platform) or .so (Linux platform) files can be imported as module imports.

Guess you like

Origin blog.csdn.net/Rolandxxx/article/details/127821937