python调用c++ so库· pybind11(一)

ocr中,为了加快后处理速度,常常使用c++来写模块被python调用,比如EAST中的lanms,psenet中的pse过程,还有pan的后处理。它们都选择了pybind11。

开发环境

简单打印例子

just_print.cpp c++ 11 语法

#include "pybind11/pybind11.h"
#include "pybind11/numpy.h"
#include "pybind11/stl.h"
#include "pybind11/stl_bind.h"

namespace py = pybind11;

namespace cpp_print{

    void cpp_print()
    {
        std::cout<<"this is cpp function!"<<std::endl;
    }
 }

PYBIND11_MODULE(just_print, m){  //这里写cpp文件名
    m.def("cpp_print", &cpp_print::cpp_print, " just print something"); // namespace名::函数名
} 

Makefile

CXXFLAGS = -I include  -std=c++11 -O3 $(shell python3-config --cflags)
LDFLAGS = $(shell python3-config --ldflags)

CXX_SOURCES = just_print.cpp

LIB_SO = just_print.so

$(LIB_SO): $(CXX_SOURCES) $(DEPS)
    $(CXX) -o $@ $(CXXFLAGS) $(LDFLAGS) $(CXX_SOURCES) --shared -fPIC

clean:
    rm -rf $(LIB_SO)

make,如果报错“g++: error: unrecognized command line option ‘-fno-plt’
”就复制打印的一长串,把-fno-plt去掉手动编译。
编译成功就有just_print.so文件

在python里调用

python
>>> from just_print import cpp_print
>>> cpp_print()
this is cpp function!

复杂例子看(二)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容