程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Swig & Python calls C code

編輯:Python

    SWIG, Simplified Wrapper and Interface Generator, It's a software development tool , It will C and C++ The program is connected with various high-level programming languages .SWIG Available for different types of target languages , Including common scripting languages , Such as Javascript、Perl、PHP、Python、Tcl and Ruby. The list of supported languages also includes non scripting languages , Such as C#,D,Go language,Java, Include Android,Lua,OCaml,Octave,Scilab and R. It also supports several kinds of interpretation and compilation Scheme Realization (Guile,MzScheme/Racket)


 

agt-get install swig

usage

1. establish C Files and header files

example.c

#include "example.h"
int fact(int n) {
if (n < 0) {
return 0;
}
if (n == 0) {
return 1;
}
else {
return n * fact(n-1);
}
}

example.h

int fact(int n);

2. To write swig Interface file   example.i

%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
int fact(int n)
  • %module The following name is the name of the encapsulated module ,Python Load the program by this name .
  • %{…%} Added between , It generally contains some function declarations and header files required by this file .
  • Last part , Declare the functions and variables to be encapsulated .

swig The simplicity of the interface file is that it is easy to write

3.   Call... Using the command line Swig Methods produce Python modular

swig -python example.i

 

It will be generated after execution 2 New file :example_wrap.c,example.py

 

4. use setup.py Generate so file

setup.py

from distutils.core import setup, Extension
example_module = Extension('_example',
sources=['example_wrap.c', 'example.cpp'],
)
setup(name='example',
version='0.1',
author="SWIG Docs",
description="""Simple swig example from docs""",
ext_modules=[example_module],
py_modules=["example"],
)

Derived .so File naming needs to start with an underscore _

Compile the generated so file

python setup.py build_ext --inplace

5.  stay C Call in language program

test.py

import _example
print(_example.fact(4))


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved