python调用c++之swig

4 篇文章 0 订阅
2 篇文章 0 订阅

一、 准备扩展模块源码

准备好需要扩展的c/c++程序,如:

/* service.h */
#ifndef SERVICE_H
#define SERVICE_H

class Service
{
    public:
        Service();
        ~Service();

        int add(int a, int b);
};

#endif

/* service.cpp */
#include "service.h"

Service::Service()
{

}

Service::~Service()
{

}

int Service::add(int a, int b)
{
    return a + b;
}

二、 编写swig接口脚本

编写 service.i SWIG接口

/* service.i  */

%module Service

%{

#define SWIG_FILE_WITH_INIT

#include "service.h"

%}

%include "service.h"

三、 通过swig封装接口

执行 swig -c++ -python service.i 指令,生成 service_wrap.cxxservice.py 文件

四、 编写安装脚本

编写 setup.py 安装脚本

from distutils.core import setup, Extension

pht_module = Extension('_Service',
                        sources=['service_wrap.cxx',
                                 'service.cpp'
                                ],
                        )

setup(name = 'Service',
        version = '0.1',
        author = 'SWIG Docs',
        description = 'Simple swig pht from docs',
        ext_modules = [pht_module], 
        py_modules = ['Service'], 
     )

五、 生成扩展模块(.so)

执行 python setup.py build_ext --inplace 指令,生成 build文件夹 和 _service.cpython-35m-x86_64-linux-gnu.so 动态库

六、 编写测试程序

编写 test.py 测试程序,测试c++扩展模块功能

import Service

x = 1
y = 2
service = Service.Service()
z = service.add(a = x, b = y)

print(z)

七、 查看测试结果

执行 python test.py 指令,查看测试结果

在这里插入图片描述

参考文献

  1. C++ 扩展python(二)简单的mpi(使用SWIG)上
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值