东方耀AI技术分享

标题: swig方式案例(py的distutils编译):python调用c/c++ [打印本页]

作者: 东方耀    时间: 2020-10-19 16:10
标题: swig方式案例(py的distutils编译):python调用c/c++


python中调用c/c++代码的使用Demo


首先准备c++的文件:test_post.h    test_post.cpp
开始编写test_post.i文件


*.i文件的语法:
%module 后面的名字是被封装的模块名称。封装口,python通过这个名称加载程序
%{  %}之间所添加的内容,一般包含此文件需要的一些函数声明和头文件。
最后一部分,声明了要封装的函数和变量,直接使用%include 文件模块头文件直接包含即可


  1. %module test_post
  2. %{
  3.   #define SWIG_WITH_INIT
  4.   #include "test_post.h"
  5. %}


  6. %include "test_post.h"
复制代码



执行
swig -python -c++ test_post.i
会生成:模块名.py和模块名_warp.cxx 两个文件


开始编写setup.py文件
  1. # -*- coding: utf-8 -*-
  2. __author__ = u'东方老师 微信:dfy_88888'
  3. __date__ = '2020/10/19 下午3:33'
  4. __product__ = 'PyCharm'
  5. __filename__ = 'setup'

  6. from distutils.core import setup, Extension
  7. import numpy
  8. import os

  9. # os.environ['CC'] = 'g++';

  10. # Extension('_pafprocess', ['pafprocess.cpp', 'pafprocess.i'],
  11. #                   swig_opts=['-c++'],
  12. #                   depends=["pafprocess.h"],
  13. #                   include_dirs=[numpy.get_include(), '.'])
  14. # 生成一个扩展模块 模块名称,必须要有下划线
  15. my_module = Extension(name='_test_post',
  16.                       sources=['test_post.cpp', 'test_post_wrap.cxx'],
  17.                       swig_opts=['-c++'])

  18. setup(name='test_post',
  19.       version='1.0',
  20.       author='jjj',
  21.       description='jjj_desc',
  22.       ext_modules=[my_module],
  23.       py_modules=["test_post"])
复制代码

利用python提供的自动化编译模块进行编译。编写一个文件setup.py
执行
python3 setup.py build_ext --inplace


最终生成了一个_test_post.cpython-36m-x86_64-linux-gnu.so 库文件


开始验证:
python3
import test_post
test_post.add(2,3)
test_post.sub(10,8)



作者: bixintao    时间: 2020-11-10 19:52
积分积分法




欢迎光临 东方耀AI技术分享 (http://www.ai111.vip/) Powered by Discuz! X3.4