Interfacing C/C++ and Python with SWIG

Slides:



Advertisements
Similar presentations
高考短文改错专题 张柱平. 高考短文改错专题 一. 对短文改错的要求 高考短文改错的目的在于测试考生判断发现, 纠正语篇中 语言使用错误的能力, 以及考察考生在语篇中综合运用英 语知识的能力. 二. 高考短文改错的命题特点 高考短文改错题的形式有说明文. 短文故事. 书信等, 具有很 强的实用性.
Advertisements

全国卷书面表达备考建议 广州市第六中学 王慧珊 Aug. 24th, 2015.
2014 年上学期 湖南长郡卫星远程学校 制作 13 Getting news from the Internet.
Presented By: 王信傑 Ricky Wang Date:2010/10/6
2007年8月龙星课程 周源源老师课程体会 包云岗 中科院计算所
Ch02物件導向程式設計 物件導向系統分析與設計.
淡水泉投资:安全稳健低回撤 长期业绩卓著 产品基本信息 基金经理简介 产品全称 银河证券-盘晟淡水泉成长1号 基金经理 赵军 受托人
How can we become good leamers
Java Programming Hygiene - for DIDC
自衛消防編組任務職責 講 義 This template can be used as a starter file for presenting training materials in a group setting. Sections Right-click on a slide to add.
2014年上海市中职校学业水平考试 英语学科总结报告
Performance Evaluation
第4章 VHDL设计初步.
程設一.
How can we be a member of the Society? You should finish the following tasks if you want to be a member of the Birdwatching Society.
天文望远镜集成建模研究 杨德华 南京天文光学技术研究所 30 NOV, 年中国虚拟天文台年会 广西师范大学 桂林
Leftmost Longest Regular Expression Matching in Reconfigurable Logic
Homework 4 an innovative design process model TEAM 7
考试与考生 --不对等与对等 邹申 上海外国语大学
優質教育基金研究計劃研討會: 經驗分享 - 透過Web 2.0推動高小程度 探究式專題研習的協作教學模式
Qtopia 编程部分要点分析 苗忠良.
第六章 应用程序结构.
Chapter 1 用VC++撰寫程式 Text book: Ivor Horton.
圖形溝通大師 Microsoft Visio 2003
中国散裂中子源小角谱仪 的实验数据格式与处理算法 报告人:张晟恺 中国科学院高能物理研究所 SCE 年8月18日
單元3:軟體設計 3-2 順序圖(Sequence Diagrams)
Special English for Industrial Robot
Decision Support System (靜宜資管楊子青)
第4章(2) 空间数据库 —关系数据库 北京建筑工程学院 王文宇.
Android 课程讲义 智能手机开发
C++ with Managed Extensions
旅游景点与度假村管理 中山大学新华学院 (Management of Attractions & Resorts) 总学时:54
创建型设计模式.
2 C++ 的基本語法和使用環境 親自撰寫和執行程式是學好程式語言的不二法門。本章藉由兩個簡單的程式,介紹C++ 程式的基本結構和開發環境,讓初學者能逐漸建立使用C++ 的信心。
Native Development Kit
编译原理专题实验 2013 西安交通大学.
iSlide® PowerPoint standard template.
第三章 项目设定.
研究地月距離的變化.
第九單元 Classes and data abstraction I
微软新一代云计算 面向企业的 Office 365 客户培训大纲
SpringerLink 新平台介绍.
PubMed整合显示图书馆电子资源 医科院图书馆电子资源培训讲座.
Decision Support System (靜宜資管楊子青)
資料結構 Data Structures Fall 2006, 95學年第一學期 Instructor : 陳宗正.
Version Control System Based DSNs
Unit 8 Our Clothes Topic1 What a nice coat! Section D 赤峰市翁牛特旗梧桐花中学 赵亚平.
计算机问题求解 – 论题1-7 - 不同的程序设计方法
Guide to a successful PowerPoint design – simple is best
中国科学技术大学计算机系 陈香兰 2013Fall 第七讲 存储器管理 中国科学技术大学计算机系 陈香兰 2013Fall.
虚 拟 仪 器 virtual instrument
中央社新聞— <LTTC:台灣學生英語聽說提升 讀寫相對下降>
-----Reading: ZhongGuanCun
徐迎晓 复旦大学软件学院 实现模型 徐迎晓 复旦大学软件学院.
Speaker: Liu Yu-Jiun Date: 2009/5/6
SpringerLink 新平台介绍.
Inheritance -II.
TEEN CHALLENGE Next Steps 核心价值观总结 CORE VALUES 青年挑战核心价值观
Chapter 10 Mobile IP TCP/IP Protocol Suite
Create and Use the Authorization Objects in ABAP
5. Combinational Logic Analysis
11月份豆油价格区间震荡 宏源期货农产品团队 张磊 2011年10月29日.
怎樣把同一評估 給與在不同班級的學生 How to administer the Same assessment to students from Different classes and groups.
Arguments to the main Function and Final Project
面向对象程序设计 C++教程 西安工业大学 于帆.
Introduction to Computer Security and Cryptography
健康按摩法 請開音樂.
陳情表之外     with 三仁 三樂 歐陽宜璋製於 /10/23.
Section 1 Basic concepts of web page
When using opening and closing presentation slides, use the masterbrand logo at the correct size and in the right position. This slide meets both needs.
Presentation transcript:

Interfacing C/C++ and Python with SWIG 隱藏之投影片 2016/9/5 2016// Interfacing C/C++ and Python with SWIG 胡連鈞 Hu, Lien Chun 電機系, Department of Electrical Engineering 國立成功大學, National Cheng Kung University Tainan, Taiwan, R.O.C 06-2757575 ext 62365, Office: 奇美樓, 6F, 95601 Email: seido5310@gmail.com Website address: http://j92a21b.ee.ncku.edu.tw/broad/index.html or http://www.ee.ncku.edu.tw/chinese/member/professor/T405-jou/T0000000c.htm

Content Abstract SWIG示範 Python Extension Building SWIG command & SWIG Examples Objects The SWIG Library The SWIG Documentation System Summary

Abstract : What is SWIG? SWIG全名是 Simplified Wrapper and Interface Generator 是一個編譯器介面 a code generator which produces glue code required to wrap C and C++ libraries. a Simplified Wrapper and Interface Generator 將C/C++與Python、Perl、Ruby程式連結 將C語言程式轉換成Python模組 Building high performance C modules Swig 全名是指 透過簡單包裝 並且 產生接口 的產生器 他可以讓原本的C/c++語言透過swig 這個工具 變成 python 或其他語言 是讓你只要會C就能轉換成python很方便的工具

Abstract C / C++ 特性 +高效率 (又小又快) +跨平台 +語法簡潔 -上手較難 (指令較多) -擴展和修改有困難 低階語言 +高效率 (又小又快) +跨平台 +語法簡潔 -上手較難 (指令較多) -擴展和修改有困難 Python 特性 高階語言 (行數少) +物件導向 (全部都是object!) +直譯式 (沒有exe檔, 可交談式互動) +跨平台 +易懂易學 強大的套件 -慢 (檔案較大)

1. Swig示範 - c轉成python Abstract SWIG示範 Python Extension Building SWIG command & SWIG Examples Objects The SWIG Library The SWIG Documentation System Summary

1. Swig示範 - c轉成python 前置作業: 安裝Ubuntu (製造Linux環境) Swig 工具下載 Python 工具下載 https://www.pcsetting.com/linux/29?page=0%2C1 Swig 工具下載 http://www.swig.org/survey.html Python 工具下載 https://www.python.org/

1. Swig示範 - c轉成python 假設一個程式碼 example.c 還需要 一個 interface file 檔 example.i .c (C code 檔) .i (interface file檔) 還需要一個.i的interface接口檔案,讓C有個接口連接swig 。格式如下

1. Swig示範 - c轉成python 將以上兩個檔案放置同一個資料夾後 →輸入指令 swig -python example.i →會產生example.py  example_wrap.c 兩個檔 接口檔案,讓C有個接口連接swig 。格式如下

1. Swig示範 - c轉成python 輸入指令 gcc -c -fpic example.c example_wrap.c -I/usr/include/python2.7 →產生example.o example_wrap.o 兩個檔 輸入指令 gcc -shared example.o example_wrap.o -o _example.so →產生example.so 動態檔 要加底線 接口檔案,讓C有個接口連接swig 。格式如下

1. Swig示範 - c轉成python

1. Swig示範 - c轉成python 輸入指令python →進入python環境 C code 輸入指令python →進入python環境 輸入code import example→載入程式碼 可利用 example.XXX() 進行 按Ctrl+D 可跳離python To provide access to C global variables, SWIG creates a special Python object called `cvar' that is added to each SWIG generated module

1. Swig示範 - c轉成python (複習一下) (interface file檔) .c (C code 檔) .o (執行檔) .py (python code 檔) swig -python example.i 3. 4. .py 檔是 Python 的原始程式碼檔案,而 Python 會在執行 .py 檔時,將 .py 的程式碼編譯成中間程式碼檔 ( byte-compiled ) 的 .pyc 檔以加快下次執行的速度。 所以,當你執行一支 .py 檔時,Python 會先看看有沒有這支 .py 檔的 .pyc 檔,如果有,而且 .py 檔的修改時間和 .pyc 檔一樣時,Python 就會讀 .pyc 檔,否則, Python 就會去讀原來的 .py 檔。 .pyc (中間程式碼檔) .so (動態檔) _wrap.c (包裝檔)

1. C轉化後python程式上執行 .i (interface file檔) .c (C code 檔)

2. Python Extension Building Abstract SWIG示範 Python Extension Building SWIG command & SWIG Examples Objects The SWIG Library The SWIG Documentation System Summary

2-1. Python Extension Building There are two basic methods for integrating C/C++ with Python Extension writing Extension writing involves the creation of new Python modules. These modules provide access to underlying C/C++ functions and variables. Embedding Embedding allows C/C++ programs to access the Python interpreter and execute Python commands. We are primarily concerned with “extension writing”. That is, providing Python access to existing C/C++ libraries. 有兩個基本的方法去整合 C/C++ 和 Python 擴展寫法 和 嵌入 擴展寫法讓 python 建立出新的架構,並且讓能夠存取C 的功能和變數 嵌入讓C能夠去存取python的編譯器和執行python的命令。 我們主要關心於擴展寫法,這可以讓python去存取 存在於C的library。

2-1. Python Extension Building Python talks to C/C++ through special “wrapper” functions .c (C code 檔) 然後Python要跟C講話需要一個包裝的功能,要先把C經過包裝 _wrap.c (包裝檔)

2-1. Python Extension Building A Complete Extension Example  _wrap.c (包裝檔) 1 完整的擴展範例 功能表 2 3

2-2. Compiling A Python Extension There are two methods Dynamic Loading. Static linking. Dynamic Loading The extension module is compiled into a shared library or DLL. When you type ‘import’, Python loads and initializes your module on the fly. Static Linking The extension module is compiled into the Python core. The module will become a new “built-in” library. Typing ‘import’ simply initializes the module. Given the choice, you should try to use dynamic loading It’s easier. It’s surprisingly powerful if used right. Dynamic Loading : 被compiled 到一個共用的library或動態連結程式庫 (Dynamic Link Library) 輸入import,pytho會動態的load和初始化你的module 靜態的: compiled 到Python 核心,modul會變成一個內建的library,輸入import只會初始化

2-2. Compiling A Python Extension 程式執行時會參照到library,其中又分動態連結與靜態連結。 使用動態連結的執行檔,他們的大小通常較小,而且在程式執行時一定要參照.so檔,在Linux裡可以用ldd指令去看某程式要參照什麼函式庫。.so檔通常放在/lib中,程式才會找到他 靜態連結的執行檔,檔案通常較大,而且在執行時不必再動態去參照函式庫。 動態函式庫 (.so)檔是可共用的,相反地,靜態函式庫(.a)則不行。

2-3. Constants .i (interface file檔) Python

2-3. Constants The following declarations are turned into Python variables #define const enum Examples : #define ICONST 5 #define FCONST 3.14159 #define SCONST "hello world" enum boolean {NO=0, YES=1}; enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; const double PI = 3.141592654;

2-4. Global Variables P.S. %readonly .i (interface file檔) Python .i

3. SWIG & SWIG Examples Abstract SWIG示範 Python Extension Building SWIG command & SWIG Examples Objects The SWIG Library The SWIG Documentation System Summary

3-1. SWIG command swig [ options ] filename

3-2. Another example (without .i) (可能只有一個function所以可以這樣用)

3-2. Another example (without .i)

3-3. Multiple Files and Modules Interfaces can be built from multiple files and libraries. Module system it very easy to reuse code in other packages. .i (interface file檔)

3-4. Derived_module & head file base.h (標頭檔) class base { public: int foo(); }; base_module.i %module base_module %{ #include "base.h" %} %include "base.h" %inline %{ ... %} inserts code into the header section and "wraps" it. derived_module.i %module derived_module %import "base_module.i" %inline %{ class derived : public base { public: int bar(); }; %}

3-5. Building Python Modules Can build Python modules out of C/C++ libraries. Example : MATLAB, OpenGL, etc… OpenGL Example The steps (summary) : Copy header files. Make a few minor changes (only about a dozen in this case). Write a few helper functions. Compile the module. .i (interface file檔) 做個微小的變動

3-5. Building Python Modules 利用程式畫圖

4. Objects Abstract SWIG示範 Python Extension Building SWIG command & SWIG Examples Objects The SWIG Library The SWIG Documentation System Summary

4-1. Object Oriented (物件導向) NON-Object Oriented Object Oriented NON-Object Oriented 變數是指鰾 Python

4-2. Pointers All derived types in SWIG are pointers. Encoded as strings with type information Example: _1008e124_Vector_p address type point .i (interface file檔) Python

4-3. Array Array are pointers .i (interface file檔) Python

4-4. Code Insertion The structure of SWIG’s output _wrap.c (包裝檔) The structure of SWIG’s output Four directives are available for inserting code %{ ... %} inserts code into the header section. %wrapper %{ ... %} inserts code into the wrapper section. %init %{ ... %} inserts code into the initialization function. %inline %{ ... %} inserts code into the header section and "wraps" it.

#This file was created automatically by SWIG 4-5. Shadow classes Can encapsulate C structures or C++ classes with a Python class. The Python class serves as a wrapper around the underlying C/C++ object (and is said to “shadow” the object). Easily built using pointers and low-level accessor functions. Contrast to writing a new Python type in C. #This file was created automatically by SWIG 能夠封裝C結構或C++ 階級 Python 用來包裝盒底層的C的 Object服務 3 . 4.在python中寫入C 建立起低階語言的連接 簡單來說 可以用C的語法在python做事情 .i (interface file檔)

4-6. Accessing Arrays of Objects %addmethods can be used to add Python specific functions .i (interface file檔) Python 存取array中任何的object相對容易 提供自然的存取 和你預期依樣 同樣的手法可以用在分層、跌代或其他的手法 Accesing arrays of any kind of object is relatively easy. Provides natural access (arrays can be manipulated like you would expect).

4-7. Complex Objects (typedef) SWIG manipulates all "complex" objects by reference The definition of an object is not required. Pointers to objects can be freely manipulated. Any "unrecognized" datatype is treated as if it were a complex object. Make sure you tell SWIG about typedef. SWIG 操縱所有的complex objects by reference 一班來說object 不用特別定義 Pointer to object 很容易 沒有特別說的datatype 會被視為 complex object

Making Sense of Objects (Summary) SWIG uses a layered approach All three modes are useful and may be mixed in the same program Use opaque pointers when access to an object’s internals is unnecessary. Use C/C++ accessor functions when occasional access to an object is needed. Use Python shadow classes when you want an interface that closely mimics the underlying C/C++ object. 若是對內部的object 不需要使用指標存取 當偶然存取要使用到Object時可以使用 Accsoor function 使用 Shadow class 可以去作為接口 模仿底層 的C object

5. The SWIG Library Abstract SWIG示範 Python Extension Building SWIG command & SWIG Examples Objects The SWIG Library The SWIG Documentation System Summary

5. The SWIG Library SWIG is packaged with a standard “library” Think of it as the SWIG equivalent of the Python library. Contents of the library : Interface definitions to common C libraries. Utility functions (array creation, pointer manipulation, timers, etc...) SWIG extensions and customization files. Support files (Makefiles, Python scripts, etc...) Using the library is easy--just use the %include directive. Code from the library files is simply inserted into your interface. .i (interface file檔)

5. The SWIG Library Example %include pointer.i Provides high level creation, manipulation, and destruction of common types Can create arrays, dereference values, etc... The cool part : uses the SWIG type-checker to automatically infer types. .i (interface file檔) Python

5. The SWIG Library : Support Files Other Library : http://www.swig.org/Doc2.0/Library.html#Library Need a Python Makefile in a hurry? 輸入指令: % swig -python -co Makefile Makefile checked out from the SWIG library % Edit it and you’re off and running.

6. The SWIG Documentation System Abstract SWIG示範 Python Extension Building SWIG command & SWIG Examples Objects The SWIG Library The SWIG Documentation System Summary

6-1. The SWIG Documentation System

6-2. Adding Additional Text

7. Summary Abstract SWIG示範 Python Extension Building SWIG command & SWIG Examples Objects The SWIG Library The SWIG Documentation System Summary

7. Summary This tutorial had 4 main goals Conclusions Promote the benefits of using Python with C/C++. Describe the process of building Python extensions. A thorough overview of using SWIG to produce modules. Discuss a few practical issues. Conclusions Integration of C/C++ with Python is a powerful tool--both for developing better C programs and for building better applications. Python is designed for extension programming. SWIG (automated tools) can greatly simplify the task of integrating C/C++ with Python. But, there are also a variety of coding issues you need to keep in mind. Many of the techniques and issues described are applicable to other Python extension tools and even other scripting languages. 1.整合C使用python 這個強大的工具,讓C program 發展得更好、能夠建立起更好的應用程序。 2.python使被設計來擴展programming 3.自動結合的工具可以有效的話簡化C和python 4. BUT 還是有些指令 issue 要去注意 5.許多所描述的技術和問題也適用於其它Python擴展工具和甚至其它腳本語言。