SWIG-使用C语言扩展Python的神器


前言

记录SWIG的一些要点


一、SWIG是什么?

SWIG(http://www.swig.org)指的是简单包装器和接口生成器,是一个适用于多种语言的工具。一方面,它让你可以使用C/C++编写扩展代码;另一方面,它自动包装这些代码,并且让这些代码在Java、Python、Tcl、Perl和Ruby等高级语言中运行。

说人话就是能够让你在脚本语言中调用C/C++函数

二、使用步骤

1. 安装步骤

此处https://blog.csdn.net/weixin_39445116/article/details/110873807
或者官网有详细解释
我自己上传的百度云链接:
链接:https://pan.baidu.com/s/1keL2BVja-u-mg9hxtNkbBQ
提取码:hsqg

2.代码示例

SWIG使用很简单,步骤为:

  1. 写一个C代码文件
  2. 编写接口文件(.i)
  3. 对接口文件运行SWIG,会生成一些额外的C语言代码
  4. 将原来的C语言代码和生成的一起编译,就会生成一个库

写代码部分

首先假设有如下example.c代码:

/* File : example.c */ 
#include <stdio.h>

int Circle (int x, int y, int radius) {
  /* Draw Circle */
  printf("Drawing the circle...\n");
  /* Return -1 to test contract post assertion */
  if (radius == 2)
    return -1;
  else
    return 1;
}

example.i文件代码:

/* File : example.i */

/* Basic C example for swig contract */
/* Tiger, University of Chicago, 2003 */

%module example

%contract Circle (int x, int y, int radius) {
require:
     x      >= 0;
     y      >= 0;
     radius >  x;
ensure:
     Circle >= 0;
}

%inline %{
extern int Circle (int x, int y, int radius);
%}

然后输入以下代码,这会生成一个example_wrap.c和example.py文件

swig -python example.i 

编译链接和使用(Linux平台下)

编译时要确定Python的include目录被包含在PATH中,或者写在命令行里面。以下代码会生成共享库,并且加载共享库

gcc -c -fpic example.c example_wrap.c -I/usr/include/python3.5/
gcc -shared example.o example_wrap.o -o _example.so

Python调用过程如下

[root@localhost simple_c]# python
Python 2.7.5 (default, Apr  2 2020, 13:16:51) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> example.Circle(1,3,4)
Drawing the circle...
1
>>>

总结

前面写了篇翻译官方的文档,但是篇幅太大,不适合入门看,现在是取其精华,放弃其中的细枝末节,就有了这篇文章。

posted @   强里秋千墙外道  阅读(76)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示