Ubuntu下swig的安装、配置与测试(用c扩展python)

1、sudo apt insall swig

安装位置默认在/usr/share/swig3.0

2、设置PATH环境变量

gedit ~/.bashrc

# 添加以下两行到bashrc中

SWIG_PATH=/usr/share/swig3.0

PATH=$PATH:$SWIG_PATH

 

#让配置文件生效

source ~/.bashrc

4、验证生效:

swig -version

5、测试

c文件:

/* File : example.c */
 
#include <time.h>
double My_variable = 3.0;
 
int my_fact(int n) {
     if (n <= 1) return 1;
     else return n*my_fact(n-1);
 }
 
int my_mod(int x, int y) {
     return (x%y);
 }
 	
char *get_time()
 {
     time_t ltime;
     time(&ltime);
     return ctime(&ltime);
 }

接口文件:

 /* example.i */
 %module example
 %{
 /* Put header files here or function declarations like below */
 extern double My_variable;
 extern int my_fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();
 %}
 
 extern double My_variable;
 extern int my_fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();

编译并生成python接口模块:

wjs@wjs-VirtualBox:~/代码/c/swig_example$ swig -python example.i

wjs@wjs-VirtualBox:~/代码/c/swig_example$ gcc -fPIC -c example.c example_wrap.c -I /usr/include/python3.6

wjs@wjs-VirtualBox:~/代码/c/swig_example$ gcc -shared -fPIC example.o example_wrap.o -o _example.so

wjs@wjs-VirtualBox:~/代码/c/swig_example$

注意:刚开始生成动态链接库.so文件时,出现如下问题:

relocation R_X86_64_PC32 against symbol `my_fact' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: 最后的链结失败: 错误的值
collect2: error: ld returned 1 exit status

这个问题解决方法很简单:在gcc每一次编译时都强制手工加上-fPIC项,这样就不会报错了;

测试:测试时,中间生成的example.py和_example.so必须在PYTHONPATH中或与测试文件在同一目录下;

test_example.py

import example
print(example.my_fact(5))
print(example.my_mod(7,3))
print(example.get_time())

运行结果:

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wjs30078111

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值