use Swig to create C/C++ extension for Python
SWIG is a software development tool that simplifies the task of interfacing different languages to C and C++ programs.
1. The SWIG %module directive specifies the name of the Python module
--this module consists of a Python source file example.py and a low-level extension module _example.so.
2. input is a interface file (*.i) or C/C++ header file,SWIG transforms it into a set of low-level procedural wrappers
(module_wrap.cxx, which later compiled to be _module.so)
Using these wrappers, SWIG generates a high-level Python proxy class (also known as a shadow class, in moudle.py)
that is, file.i is transformed into a file file_wrap.c or file_wrap.cxx ; generate proxy class files in the target language
3. Everything in the %{ ... %} block is simply copied verbatim to the resulting wrapper file created by SWIG.
(the included staff are need to compile module_wrap.cxx)
4. %immutable directive stays in effect until it is explicitly disabled or cleared using %mutable.(vars with const decorator)
5. To create a constant, use #define, enum , or the %constant directive
6. Global functions are wrapped as new Python built-in functions.
7. SWIG creates a special object called `cvar' that is added to each SWIG generated module.
Global variables are then accessed as attributes of this object.
8. Most of SWIG's operation is controlled by special directives that are always preceded by a "%"
to distinguish them from normal C declarations
9. all variable declarations, regardless of any use of const, are wrapped as global variables.
If a declaration happens to be declared as const, it is wrapped as a read-only variable
10. It'a a bad idea to pass a string from scripting language to C char * (of which the value is possible to be changed),
for in python, string is a tuple (const!!)
11. except the basic types, For everything else (structs, classes, arrays, etc...) SWIG applies a very simple rule :
Everything else is a pointer
12. Arrays are fully supported by SWIG, but we need to create extra helper function
13. director feature can used to realize polymorphism
14. the code inside an %inline %{... %} block is given to both the C compiler and SWIG

Exmaple:
// file:llist.h
class llist
{
public:
int getvalue();
void setvalue(int a);
int value;
}; class llistA:public llist
{
public:
void printt(llist a);
void printt(llist* a);
}; struct Vector {
int a;
};
/* file: example.h */
#define MAXAA 6
int Foo;
char * path = "hello";
int fact(int n);
double cal(double X);
#include "llist.h"
#include "example.h"
#include <iostream>
using namespace std; int fact(int n)
{
if (n < ) return ;
if (n == ) return ;
else return n* fact(n-);
} double cal(double x)
{
Foo += (int)x * MAXAA;
return x *;
}; void strprint(const char * s, int a)
{
cout << s << " with int value: " << a << endl;
} llist getlist(Vector &vecta, llist * b)
{
b->setvalue(vecta.a+b->getvalue());
return *b;
} int llist::getvalue() { return this->value;}
void llist::setvalue(int a) { this->value = a;}
void llistA::printt(llist a) { cout << "llistA a" << endl;}
void llistA::printt(llist* a) { cout << " pointer of llistA a " << endl;}
// file : example.i %module example
%{
// the following macro will insert module init code in moudle_wrap.cxx
#define SWIG_FILE_WITH_INIT #include "llist.h" extern int Foo;
extern char * path; int fact(int n);
double cal(double X);
void strprint(const char *, int a);
llist getlist(Vector& vecta, llist * b);
%} extern int Foo;
%immutable;
extern char * path;
%mutable;
%constant const char * brig = "/usr/local"; class llist
{
public:
int getvalue();
void setvalue(int a);
int value;
}; class llistA:public llist
{
public:
void printt(llist a);
void printt(llist* a);
}; class Vector {
int a;
}; int fact(int n);
double cal(double X);
void strprint(const char *, int a);
llist getlist(Vector& vecta, llist * b);
to build it (bash):
#------------------C------------------------------
#swig -python example.i
#python setup.py build_ext --inplace
#
#----------------C++----------------------------
swig -c++ -python example.i
g++ -O2 -fPIC -c example.cpp
g++ -O2 -fPIC -c example_wrap.cxx -I/usr/include/python3.5m
g++ -shared example.o example_wrap.o -o _example.so
test code:
#!/usr/bin/env python
import example
print("call function fact: ", example.fact(5))
print("call function cal : ", example.cal(4.5))
print("print global value: ", example.cvar.Foo)
example.cvar.Foo = 6;
example.cal(1)
print("print global value Foo : ", example.cvar.Foo)
print("print global value path: ", example.cvar.path)
print(example.cvar.brig)
#print(example.cvar.MAXAA)
# be careful, it's "vetor()" not "vector"
v = example.Vector()
v.a = 5;
list = example.llist()
list.value = 6
lista = example.llistA()
lista.setvalue(8)
print("call member fuction of llistA")
lista.printt(list)
lista.printt(lista)
print("vector v : ", v)
print("class list : ", list)
print("class listA : ", lista)
listc = example.getlist(v, list)
print("instnce listc : ", listc)
print("value of listc: ", listc.getvalue())
use Swig to create C/C++ extension for Python的更多相关文章
- How to Create an PostgreSQL Extension
转自:https://severalnines.com/blog/creating-new-modules-using-postgresql-create-extension Extensibilit ...
- [Tools] Create a Chrome Extension
Creating a Chrome extension requires a manifest.json file which defines how your extension will beha ...
- How to create PDF files in a Python/Django application using ReportLab
https://assist-software.net/blog/how-create-pdf-files-python-django-application-using-reportlab CONT ...
- [Python] Create a minimal website in Python using the Flask Microframework
How to install Flask Use Flask to create a minimal website Build routes in Flask to respond to websi ...
- [Python] Create Unique Unordered Collections in Python with Set
A set is an unordered collection with no duplicate items in Python. In this lesson, you will learn h ...
- [Python] Create a Log for your Python application
Print statements will get you a long way in monitoring the behavior of your application, but logging ...
- python pip使用报错: Fatal error in launcher: Unable to create process using '"c:\python27\python.exe" "C:\Python27\Scripts\pip.exe" '
在一个系统中,如果同时存在python2和python3,在cmd.exe程序下执行pip.pip2或者pip3均会报错. 如何解决: 如果是在python3环境下,使用pip安装扩展库,可以使用以下 ...
- SWIG 3 中文手册——9. SWIG 库
目录 9 SWIG 库 9.1 %include 指令与库搜索路径 9.2 C 数组与指针 9.2.1 cpointer.i 9.2.2 carrays.i 9.2.3 cmalloc.i 9.2.4 ...
- Call Directory Extension 初探
推荐序 本文介绍了 iOS 10 中的 Call Directory Extension 特性,并且最终 Demo 出一个来电黑名单的 App. 作者:余龙泽,哈工大软件工程大四学生,之前在美图公司实 ...
随机推荐
- HDU 1046(最短路径 **)
题意是要在一个矩形点阵中求能从一点出发遍历所有点再回到起始点的最短路径长度. 不需要用到搜索什么的,可以走一个“梳子型”即可完成最短路径,而情况可以被分成如下两种: 一.矩形的长或宽中有偶数,则可以走 ...
- HDU 1036(平均速度 **)
题意是求出跑了 n 圈每圈 m km 的个人的平均速度. 控制格式,特别注意,题意是输出 -:--:-- 的该人成绩作废,但要把他其他的成绩输进去,不能直接就 break ,输出也就只有一个 - ,而 ...
- Spark源码剖析 - SparkContext的初始化(二)_创建执行环境SparkEnv
2. 创建执行环境SparkEnv SparkEnv是Spark的执行环境对象,其中包括众多与Executor执行相关的对象.由于在local模式下Driver会创建Executor,local-cl ...
- C#下RSA算法的实现(适用于支付宝和易宝支付)
RSA算法代码: using System; using System.Collections.Generic; using System.Text; using System.IO; using S ...
- TTS与MediaPlayer混合使用
package com.xxx.xxx.Util; import android.content.Context; import android.media.MediaPlayer; import a ...
- 基于DSP的IS95正向业务信道模块设计
**定时20ms循环处理话音数据包*** *伪指令不占空间不影响执行速度,只是定义和描述但对汇编链接有重要指示作用 ********************************* .title & ...
- linux下有名管道进程通信
一.任务 1.学习mkfifo等函数: 2.了解有名管道的特点.阻塞打开与非阻塞打开等: 3.编写一个关于有名管道进程通信的程序,并运行. 二.相关概念 1.相关函数 创建有名管道的函数是mkfifo ...
- python 的基础 学习 第七天 is id 编码的补充
1,== 两个等号比较的是数值,is比较的是内存地址.print(id())查看的内存地址. 小数据池只存在于数字与字符串中,数字 是 -5^^256,是为了节省空间. 字符串1,如果含有特殊字符 ...
- tidb调研
TiDB是新一代开源分布式 NewSQL 数据库,相比较于我们常见的数据库MySQL,TiDB具有水平伸缩.强一致性的分布式事务.基于 Raft 算法的多副本复制等特性.同时,TiDB兼容MySQL生 ...
- META-INF文件夹中的MANIFEST.MF 的作用
manifest文件是用来描述jar包的,它描述了该jar包的代码是谁的,什么版本,使用什么版本的类库等等....具体如下: 1.基础格式 manifest 文件的格式是很简单的,每一行都是 名-值 ...