您的位置:首页 > 编程语言 > C语言/C++

使用swig在python中调用c++代码

2017-05-13 22:36 806 查看

1. 使用sudo apt install swig来按照swig

2. 编写对应的.i文件

假设我们编写的c++文件和.h文件如下:

/* File: example.cpp */

#include "example.h"

int fact(int n) {
if (n < 0){ /* This should probably return an error, but this is simpler */
return 0;
}
if (n == 0) {
return 1;
}
else {
/* testing for overflow would be a good idea here */
return n * fact(n-1);
}
}

/* File: example.h */

int fact(int n);

则对应的.i文件如下:
/* File: example.i */
%module example

%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}

int fact(int n);


3. 生成对应的.example_wrap.cxx和example.py.

运行命令:swig -c++ -python example.i

4. 使用 distutils工具编译

首先生成一个setup.py文件

#!/usr/bin/env python

"""
setup.py file for SWIG example
"""

from distutils.core import setup, Extension

example_module = Extension('_example',
sources=['example_wrap.cxx', 'example.cpp'], #一定要把cpp源文件包含,如果该源文件包含了别的依赖,则应该也包含进来
)

setup (name = 'example',
version = '0.1',
author      = "SWIG Docs",
description = """Simple swig example from docs""",
ext_modules = [example_module],
py_modules = ["example"],
)


然后使用命令python setup.py install编译生成即可

参考链接,第31.2 Preliminaries
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: