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. 作者:余龙泽,哈工大软件工程大四学生,之前在美图公司实 ...
随机推荐
- 关于Ant脚本
在开发中,一个项目要经历单元测试l,集成测试,系统测试,测试过程中可能要不断修改代码,Ant脚本,通过一个xml文件,封装一系列繁琐又常用的操作,通过Ant指令执行xml脚本来批处理创建删除任务,编译 ...
- Spark源码解析 - Spark-shell浅析
1.准备工作 1.1 安装spark,并配置spark-env.sh 使用spark-shell前需要安装spark,详情可以参考http://www.cnblogs.com/swordfall/p/ ...
- 转 -- Vim 常用快捷键
``` 全选(高亮显示):按esc后,然后ggvG或者ggVG 全部复制:按esc后,然后ggyG 全部删除:按esc后,然后dG 解析: gg:是让光标移到首行,在vim才有效,vi中无效 v : ...
- 055、创建macvlan网络 (2019-03-22 周五)
参考https://www.cnblogs.com/CloudMan6/p/7364332.html 创建macvlan网络,需要指定使用哪块物理网卡进行通信 -o parent=ens1 ...
- [Android] Android 去掉界面标题栏的方法
Android 去掉界面标题栏的方法 这个首先要区分当前Activity 是继承了 Activity 类 ,还是 AppCompatActivity 类 情况一:创建的activity默认继承了App ...
- es6 javascript对象方法Object.assign() 对象的合并复制等
Object.assign方法用于对象的合并,将源对象( source )的所有可枚举属性,复制到目标对象( target ). 详细使用稳步到前辈: http://blog.csdn.net/qq_ ...
- 1、PHP入门二维数组与循环
<?php $two=array(array(2,3),1=>array(1,2,3),2=>array(4,5,6)); echo $two[1][0];//输出1 echo $t ...
- ps 命令的十个简单用法【转】
注记 ps 命令有两种不同的语法风格 —— BSD 与 UNIX 两种风格.新手常常对这两种形式产生误解,因此我们有必要在这里作一个简单的说明: ps aux 与 ps -aux 是不同的,例如 -u ...
- 十九、Linux 进程与信号---环境表
19.1 环境表 19.1.1 介绍 这是启动例程的第二各作用,搜集环境表,然后传递给主函数. 环境表就是一个指针数组. 环境表 每个进程都有一个独立的环境表 初始的环境表继承自父进程 主函 ...
- springboot08-jpa-mysql
1.主要pom依赖: <!--jpa--> <dependency> <groupId>org.springframework.boot</groupId&g ...