SWIG is a software development tool that connects programs written in C and C++ with a variety of high-level programming languages. SWIG is used with 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#, Common Lisp (CLISP, Allegro CL, CFFI, UFFI), D, Go language, Java including Android, Lua, Modula-3, OCAML, Octave, Scilab and R. Also several interpreted and compiled Scheme implementations (Guile, MzScheme/Racket, Chicken) are supported. SWIG is most commonly used to create high-level interpreted or compiled programming environments, user interfaces, and as a tool for testing and prototyping C/C++ software. SWIG is typically used to parse C/C++ interfaces and generate the ‘glue code’ required for the above target languages to call into the C/C++ code. SWIG can also export its parse tree in the form of XML and Lisp s-expressions. SWIG is free software and the code that SWIG generates is compatible with both commercial and non-commercial projects.
首先,写一个接口文件
Now, in order to add these files to your favorite language, you need to write an “interface file” which is the input to SWIG. An interface file for these C functions might look like this :
/* example.i */
%module example
%{
/* Put header files here or function declarations like below */
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
%}
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
Example:
%module segmenter_jni
%include "std_string.i"
%javaconst(1);
/* Map Java short[] to C++ short* */
%typemap(jni) short * "jshortArray"
%typemap(jtype) short * "short[]"
%typemap(jstype) short * "short[]"
%typemap(javain) short * "$javainput"
%typemap(in) short * {
$1 = (short *) JCALL2(GetShortArrayElements, jenv, $input, 0);
}
%typemap(freearg) short * {
if ($1) {
JCALL3(ReleaseShortArrayElements, jenv, $input, (short *) $1, 0);
}
}
%typemap(argout) short * {
JCALL3(ReleaseShortArrayElements, jenv, $input, (short *) $1, 0);
$1 = NULL;
}
%{
#include "../../engine/vad/segmenter.h"
%}
#define __ANDROID__ 1
%include "../../engine/vad/segmenter.h"
mkdir -p swig/speex
swig -outcurrentdir -I../../ -outdir ./swig/speex -c++ -java -package com.xxxx.be.xxxx.speex.jni ../jni/speex.i
然后把生成的cxx文件和c的源文件放在一起,编译成一个so库。再通过java调用。
本文介绍SWIG这一软件开发工具,该工具用于连接C/C++程序与多种高级编程语言。SWIG支持包括JavaScript、Python等在内的多种目标语言,并能生成‘粘合代码’使这些语言能够调用C/C++代码。此外,文章还提供了创建SWIG接口文件的具体实例。
501

被折叠的 条评论
为什么被折叠?



