SWIG构建Jni代码

Swig中文学习地址:http://www.swig.org/translations/chinese/index.html
Java 文档http://www.swig.org/Doc1.3/Java.html
下载安装最新版本,并设置环境变量
导入ndk-simple-hellojni项目
在jni目录下新建Unix.i文件

%module Unix
%{
#include <unistd.h>
%}
typedef unsigned int uid_t;
extern uid_t getuid(void);

%module Unix为暴露的组建名称,用%预处理

调用Swig,新建com.apress.swig包名

swig -java -package com.apress.swig -outdir src/com/apress/swig jni/Unix.i

新建my-swig-generate.mk文件

ifndef MY_SWIG_PACKAGE
   $(error MY_SWIG_PACKAGE is not defined.)
endif

MY_SWIG_OUTDIR:=$(NDK_PROJECT_PATH)/src/$(subst .,/,$(MY_SWIG_PACKAGE))
ifndef MY_SWIG_TYPE
    MY_SWIG_TYPE:=C
endif

#ifeq($(MY_SWIG_TYPE),cxx)
#   MY_SWIG_MODE:=c++
#else
#   MY_SWIG_MODE:=  
#endif

LOCAL_SRC_FILES+=$(foreach MY_SWIG_INTERFACE,\
      $(MY_SWIG_INTERFACES),\
      $(basename $(MY_SWIG_INTERFACE))_wrap.$(MY_SWIG_TYPE))

#LOCAL_CPP_EXTENSION+=.cxx

%_warp.$(MY_SWIG_TYPE) : %.i \
   $(call host-mkdir,$(MY_SWIG_OUTDIR)) \
   swig -java \
   $(MY_SWIG_MODE)  \
   -package $(MY-SWIG_PACKAGE)  \
   -outdir $(MY_SWIG_OUTDIR)   \
   $<       

然后在Android.mk文件中定义:
MY_SWIG_PACKAGE:包名
MY_SWIG_INTERFACES:Swig接口文件
MY_SWIG_MODE:类型 c/c++

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := hello-jni.c
MY_SWIG_PACKAGE := com.apress.swig
MY_SWIG_INTERFACES := Unix.i
MY_SWIG_TYPE := c
include $(LOCAL_PATH)/my-swig-generate.mk
include $(BUILD_SHARED_LIBRARY)

然后编译。

全局变量

Swig没有全局变量,定义一个局部变量,使用getset调用
常量定义#define 或者%constant

/* Constant using define directive. */
#define MAX_WIDTH 640;
/* Constant using %constant directive. */
%constant int MAX_HEIGHT = 320;

可通过jni方法改变

%module Unix
...
/* Constant using define directive. */
%javaconst(1);
#define MAX_WIDTH 640
/* Constant using %constant directive. */
%javaconst(0);
%constant int MAX_HEIGHT = 320;

生成结果

package com.apress.swig;
public interface UnixConstants {
public final static int MAX_WIDTH = 640;
public final static int MAX_HEIGHT = UnixJNI.MAX_HEIGHT_get();
}

编译时常量MAX_WIDTH 和运行时常量MAX_HEIGHT

只读变量

%module Unix
/* Enable the read-only mode. */
%immutable;
extern int readOnly;

set get 变量

/* Disable the read-only mode. */
%mutable;
extern int readOnly;

枚举

enum { ONE = 1, TWO = 2, THREE, FOUR }; 没定义类型
enum Numbers { ONE = 1, TWO = 2, THREE, FOUR };定义类型,无法用switch

%include “enumtypeunsafe.swg”
enum Numbers { ONE = 1, TWO = 2, THREE, FOUR };可以用switch

命名枚举
%include “enums.swg”
enum Numbers { ONE = 1, TWO = 2, THREE, FOUR };定义类型,用switch

结构体

struct Point {
int x;
int y;
};

C++指针

修改android.mk文件的MY_SWIG_TYPE := cxx
获取指针,指针引用,值

/* By pointer. */
void drawByPointer(struct Point* p);
/* By reference */
void drawByReference(struct Point& p);
/* By value. */
void drawByValue(struct Point p);

定义方法

void func(int a = 1, int b = 2, int c = 3);设置默认值

重载函数

void func(double d);
void func(int i);

猜你喜欢

转载自blog.csdn.net/a346492443/article/details/50887732
JNI