东方耀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 文件模块头文件直接包含即可
%module test_post
%{
#define SWIG_WITH_INIT
#include "test_post.h"
%}
%include "test_post.h"
复制代码
执行
swig -python -c++ test_post.i
会生成:
模块名.py和模块名_warp.cxx 两个文件
开始编写setup.py文件
# -*- coding: utf-8 -*-
__author__ = u'东方老师 微信:dfy_88888'
__date__ = '2020/10/19 下午3:33'
__product__ = 'PyCharm'
__filename__ = 'setup'
from distutils.core import setup, Extension
import numpy
import os
# os.environ['CC'] = 'g++';
# Extension('_pafprocess', ['pafprocess.cpp', 'pafprocess.i'],
# swig_opts=['-c++'],
# depends=["pafprocess.h"],
# include_dirs=[numpy.get_include(), '.'])
# 生成一个扩展模块 模块名称,必须要有下划线
my_module = Extension(name='_test_post',
sources=['test_post.cpp', 'test_post_wrap.cxx'],
swig_opts=['-c++'])
setup(name='test_post',
version='1.0',
author='jjj',
description='jjj_desc',
ext_modules=[my_module],
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