利用SWIG实现python调用C
系统版本:Ubuntu16.04
安装build-essential,安装了该软件包,编译c/c++所需要的软件包也都会被安装。
sudo apt-get install build-essential
安装python3-dev
sudo apt install swig python3-dev
sudo apt install swig
export SWIG_PATH=/usr/share/swig3.0
export PATH=$PATH:$SWIG_PATH
设置完可以后查看环境变量是否安装好
echo $PATH
example.c
#include <time.h>
double My_variable = 3.0;
int fact(int n)
{
if (n <= 1) return 1;
else return n*fact(n-1);
}
int my_mod(int x, int y)
{
return (x%y);
}
char get_time()
{
time_t ltime; time(<ime); return ctime(<ime);
}
test.py
import example
print('My_varaiable: %s' % example.cvar.My_variable)
print('fact(5): %s' % example.fact(5))
print('my_mod(7,3): %s' % example.my_mod(7,3))
print('get_time(): %s' % example.get_time())
example.h
#ifndef EXAMPLE_H
#define EXAMPLE_H
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
#endif
example.i
%module example
%{
#include "example.h"
%}
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
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.c', 'example.c'],
)
setup (name = 'example',
version = '0.1',
author = "SWIG Docs",
description = """Simple swig example from docs""",
ext_modules = [example_module],
py_modules = ["example"],
)
手动编译动态模块
编译前,需要把example.i文件转换成example_wrap.c和example.py两个文件。
命令行输入:
swig -python example.i
静态链接(需要预先编辑好setup.py)在某些机器上的动态加载支持受到限制,所以有时是必要的
python setup.py build_ext --inplace
测试 命令行输入
python test.py
参考网址:
http://www.swig.org/Doc3.0/Python.html#Python_nn9
https://note.qidong.name/2018/01/hello-swig-example/