create the file jni/example.c
Code: Select all
/* File : example.c */
/* A global variable */
double Foo = 3.0;
/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) {
int g;
g = y;
while (x > 0) {
g = x;
x = y % x;
y = g;
}
return g;
}
Note:
the file name is example.c and so the module will be called example
This code exposes a global variable Foo and a function gcd.
These will be the only properties the java can call.
Based on this data, create a SWIG interface file for this C code, called jni/example.i:
Code: Select all
/* File : example.i */
%module example
%inline %{
extern int gcd(int x, int y);
extern double Foo;
%}
now, create the C interface to be used in java:
$ swig -java -package org.swig.simple -outdir src/org/swig/simple -o jni/example_wrap.c jni/example.i
create the make file jni/Android.mk
Code: Select all
# File: Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := example
LOCAL_SRC_FILES := example_wrap.c example.c
include $(BUILD_SHARED_LIBRARY)
from the project root folder, build the native with:
$ ndk-build
Compile thumb : example <= example_wrap.c
Compile thumb : example <= example.c
SharedLibrary : libexample.so
Install : libexample.so => libs/armeabi/libexample.so
ndk has created libs/armeabi/libexample.so to be installed on your device
Keep in mind, by default ndk-buld will only build for ARM5 (EABI5)
if you want your native software built for any other platform, use:
ndk-build APP_ABI=armeabi armeabi-v7a x86 mips
or APP_ABI=all to build it for all the platforms
alternatively, in the same directory of the Android.mk you can add a new file:
Application.mk
Code: Select all
APP_ABI := all
How to call the C from JAVA:
Code: Select all
/** Calls into C/C++ code */
public void nativeCall()
{
// Call our gcd() function
int x = 42;
int y = 105;
int g = example.gcd(x,y);
// Manipulate the Foo global variable
// Output its current value
double foo = example.getFoo();
// Change its value
example.setFoo(3.1415926);
// Restore value
example.setFoo(foo);
}
/** static constructor */
static {
System.loadLibrary("example");
}
note how you never declare example as you load it in System.loadLibrary("example");
also, beside it's never defined, SWIG lets you use example.getFoo() and example.setFoo(foo)