Writing Native Code for Android Systems. Why ndk There exist large c++ code libraries – E.g., Audio and video compression, e.g., Ogg Vorbis, The LAME.

Slides:



Advertisements
Similar presentations
Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
Advertisements

CS 450 Module R4. R4 Overview Due on March 11 th along with R3. R4 is a small yet critical part of the MPX system. In this module, you will add the functionality.
Makefiles. makefiles Problem: You are working on one part of a large programming project (e. g., MS Word).  It consists of hundreds of individual.c files.
Writing Native Code for Android Systems. Why ndk (native developers kit) There exist large c/c++ code libraries – E.g., Audio and video compression, e.g.,
Inlining Java Native Calls at Runtime (CASCON 2005 – 4 th Workshop on Compiler Driven Performance) Levon Stepanian, Angela Demke Brown Computer Systems.
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
Hello world Follow steps under the sections “Create an AVD” and “Create a New Android Project” at
Java Native Interface Modified from CS587x Lecture Department of Computer Science Iowa State University.
I Dream of JNI When it absolutely, positively has to be written in COBOL... shudder.
mbe/pa/olm 1 Integration of BETA with Eclipse eTX presentation Barcelona 2004 Peter Andersen Mads Brøgger Enevoldsen Ole Lehrmann Madsen.
Unix Continuum of Tools Do something once: use the command line Do something many times: –Use an alias –Use a shell script Do something that is complex.
Administrivia No class next Monday (May 2) Enjoy extra time on P3. ;-) Reading 3 available “Reflections on Trusting Trust”, Ken Thompson No written summary.
Session 1 CS-240 Data Structures Binghamton University Dick Steflik.
Java Native Interface (JNI). JNI Linking Java and C code.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Android Tutorial Android Written in Java Utilizes Dalvik VM – Just in time (JIT) compilation since Android 2.2.
COMP 14: Intro. to Intro. to Programming May 23, 2000 Nick Vallidis.
Writing Methods. Create the method Methods, like functions, do something They contain the code that performs the job Methods have two parts.
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
CS162B: Assembly and C Jacob T. Chan. Objectives ▪ System calls ▪ Relation of System calls to Assembly and C ▪ Special System Calls (exit, write, print,
Java Native Interface CS587x Lecture Department of Computer Science Iowa State University.
Introduction to Python
What is Android NDK ● A toolset that lets you embed in you app native source code ● C, C++(recently supported December 2010) and assembly(?) ● It is supported.
Hello world Follow steps under the sections “Create an AVD” and “Create a New Android Project” at
3D graphics on Android projects based on native code
Guidelines for Homework 6. Getting Started Homework 6 requires that you complete Homework 5. –All of HW5 must run on the GridFarm. –HW6 may run elsewhere.
Rutgers University Excellence Campaign 2/20/2004 Java Native Interface Tutorial Xiaolin Li Rutgers.
Java Introduction to JNI Prepared by Humaira Siddiqui.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
CSC Java Programming, Fall, 2008 Week 2: Java Data Types, Control Constructs, and their C++ counterparts, September 4.
SCRIPTING II/III References:
Android Cross Build and SUSI_3.02 Environments Settings Modify the file android_env.mak to fit your Android version and source path $vim SUSI_3.02/
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
CIT 590 Intro to Programming First lecture on Java.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 15: More-Advanced Concepts.
Chapter 2: Java Fundamentals
C Hints and Tips The preprocessor and other fun toys.
C Programming in Linux Jacob Chan. C/C++ and Java  Portable  Code written in one system and works in another  But in C, there are some libraries that.
Android JNI and JAR Library JNI Library 1. JNI *.c sources file must include jni header file jni.h #include 2. In Make file CFLAGS must add -I $(NDK_INC)/
Mixing integer and floating point numbers in an arithmetic operation.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Slide Advanced Programming 2004, based on LY Stefanus's slides Native Methods.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
C++ (intro) Created by Hwansoo Han Edited by Ikjun Yeom.
CIS 234: Java Methods Dr. Ralph D. Westfall April, 2010.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Java 变量类型与 native 变量类型 java 类型 native 类型描述对应的 C 类型 booleanjbooleanunsigned 8 bitsunsigned char bytejbytesigned 8 bitschar jcharunsigned 16 bitsunsigned.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). After today you should know everything you need for assignment.
Functions, Scope, and The Free Store Functions Functions must be declared by a function prototype before they are invoked, return_type Function_name(type,
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
1 ENGI 2420 Structured Programming (Lab Tutorial 7) Memorial University of Newfoundland.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
C is a high level language (HLL)
Programming for Interactivity Professor Bill Tomlinson Tuesday & Wednesday 6:00-7:50pm Fall 2005.
Execution ways of program References: www. en.wikipedia.org/wiki/Integrated_development_environment  You can execute or run a simple java program with.
1 Building a program in C: Preprocessor, Compilation and Linkage.
Python C API overview References:
Hank Childs, University of Oregon April 13 th, 2016 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / /
Eclipse.
Working with Java.
Types for Programs and Proofs
Lecture Note Set 1 Thursday 12-May-05
C Basics.
Java Intro III.1 (Fr Feb 23).
null, true, and false are also reserved.
Programs and Classes A program is made up from classes
SPL – PS1 Introduction to C++.
Presentation transcript:

Writing Native Code for Android Systems

Why ndk There exist large c++ code libraries – E.g., Audio and video compression, e.g., Ogg Vorbis, The LAME Project (mp3),.. OpenGL OpenSL ES – Low level audio Advanced CPU features – E.g., some ARM cpu support the NEON instruction set for signal and video processing

App are mixed java and c/c++ The java app is like a regular app. The java app is started by os. – It is not possible to have a stand alone c++ program (not sure, it might be) The c++ program is placed in a shared library – Shared libraries have names like libMyProgram.so The application package (.apk) will include the java app and the shared library jni (Java Native Interface) must be used to move data between java and c++

Outline of Steps Write c++ code in MyProject/jni Describe project sources in MyProject/jni/Android.mk – Like a make file, but much easier Build project by running the command../android-ndk-r5b/ndk-build from your MyProject directory – ndk-build is like make ndk-build – Builds Ndk-build clean – Cleans everything – Generates shared lib (libXX.so file) and places it in correct directory so the java program can get it Make.apk file by building app in eclipse – Important: whenever you make a change in the c++ program, of coruse, you need to run ndk-build. But, you also must rerun the java compile. To do this, make a trivial change in your java code and resave.

HelloJni Make new app called – Package: edu.udel.eleg454.HelloJni – Activity Name: HelloJni – Project: HelloJni Make new subdirectory in project call jni – i.e., HelloJni/jni In jni directory make new file called – MyHelloJni.cpp In this file, put – #include – extern "C" { – JNIEXPORT jstring JNICALL – Java_edu_udel_eleg454_helloJni_HelloJni_stringFromJNI( JNIEnv* env, – jobject thiz ) – { – return env->NewStringUTF("Hello from JNI!"); – } Save file Important: function names must be exactly correct – Java_packageNameWithDotReplacedByUnderScore_JavaClassNameThatWillCallThisFunction_functionName

Android.mk In HelloJni/jni make new file called Android.mk Put the following in Android.mk – LOCAL_PATH := $(call my-dir) – include $(CLEAR_VARS) – LOCAL_MODULE := HelloJni – LOCAL_SRC_FILES := HelloJni.cpp – include $(BUILD_SHARED_LIBRARY) Note that LOCAL_MODULE is the module name Build library – Open terminal. – Cd dir to /HelloJni/jni – Run build /ndk-build – Check that libHelloJni.so is created

In java HelloJni After public class HelloJni extends Activity { – public native String stringFromJNI(); // the c++ function name – static { – System.loadLibrary("HelloJni"); // shared lib is called libHelloJni.so. // this name is from the LOCAL_MODULE part of the Android.mk file – } – Note: HelloJni is our In onCreate, after setContentView(R.layout.main); put – Log.e("debug","calling jni"); – Log.e("debug",stringFromJNI()); // last part of name of c++ function – Log.e("Debug","done"); Run and check log Note: public native … allows any function to be defined. But when this function is called, the shared library must have already been loaded (via System.loadLibrary)

play Change c++ function to be make string – Hello from JNI 2 Instead of – Hello from JNI! Rebuild and run from eclipse – Log does not show anything. Not even an error In eclipse make trivial change (delete and add ;) Run, and everything is ok

C++ Function name Change c++ function name. recompile and see error in LogCat – “no implementation found for native …” Make a new class called TestJni Move jni stuff into TestJni Run and see error Change function name from – Java_edu_udel_eleg454_helloJni_HelloJni_stringFrom JNI To – Java_edu_udel_eleg454_helloJni_TestJni_stringFromJ NI And runs ok

Logging from c++ In cpp file, add – #include In Android.mk add – LOCAL_LDLIBS := -llog In function add – __android_log_print(ANDROID_LOG_INFO, “DEBUG", “Here we are");

Passing strings from java to c++ with JNI In java code, make function arg include a string – Change public native String stringFromJNI(); – To public native String stringFromJNI(String name); – And change Log.e("debug",stringFromJNI()); – To Log.e("debug",stringFromJNI("string para")); In c++ code – Change JNIEXPORT jstring JNICALL Java_edu_udel_eleg454_helloJni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz) – To JNIEXPORT jstring JNICALL Java_edu_udel_eleg454_helloJni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz, jstring javaString ) – And add const char *str = env->GetStringUTFChars(javaString, 0); // convert java string to c++ str __android_log_print(ANDROID_LOG_INFO, "DEBUG", str); // do something env->ReleaseStringUTFChars(javaString, str); // release str Build, compile, run Note: after release, str is no longer valid

Passing int, floats, etc to c++ In java – Change public native String stringFromJNI(); – To public native String stringFromJNI(int val); – And change Log.e("debug",stringFromJNI()); – To int i = 100; Log.e("debug",stringFromJNI(i)); In c++ – Change JNIEXPORT jstring JNICALL Java_edu_udel_eleg454_helloJni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz) – To JNIEXPORT jstring JNICALL Java_edu_udel_eleg454_helloJni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz, jint ji ) – And comment out const char *str = env->GetStringUTFChars(javaString, 0); env->ReleaseStringUTFChars(javaString, str); – Add char str[80]; sprintf(str,"data is %d",ji); // be sure to add #include __android_log_print(ANDROID_LOG_INFO, "DEBUG", str); Build, compile, run

Jni Data types C++ type = jave type unsigned char = jboolean signed char = jbyte unsigned short = jchar Short = jshort Long = jlong Long long = jlong __int64 = jlong float = jfloat double = jdouble

Passing arrays of ints to c++ In java – Define function to take int array as argument Replace – public native String stringFromJNI(); With – public native String stringFromJNI(int[] val); – In onCreate Make array – int[] ints = new int[]{1,1,2,3,5,8,13}; Call function with ints as augment – Log.e("debug",stringFromJNI(ints));

Passing arrays of ints to c++ In c++ – Define function to take array as argument JNIEXPORT jstring JNICALL Java_edu_udel_eleg454_helloJni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz, jintArray jiArray ) – Get size of array jsize arrayLength = env->GetArrayLength(jiArray); char str[80]; __android_log_print(ANDROID_LOG_INFO, "DEBUG", str); – Get pointer to array jint *data = env->GetIntArrayElements(jiArray, 0); – Do something with data for (int i=0; i<arrayLength; i++) { – sprintf(str,"val %d is %d",i,data[i]); – __android_log_print(ANDROID_LOG_INFO, "DEBUG", str); – data[i] = i; } – Release pointer env->ReleaseIntArrayElements(jiArray, data, 0); Build, compile, run

More passing arrays to c++ env->ReleaseIntArrayElements(jiArray, data, 0); – Last argument is 0 => data is copied back to java and java can delete data array – Last argument is JNI_COMMIT => data is copied back, but java should not delete the array – Last argument is JNI_ABORT => data is not copied back and java can delete Check if the data was changed in c++ – In java, after Log.e("debug",stringFromJNI(ints)); add for (int i=0; i<ints.length; i++) { Log.e("DEBUG","ret val["+i+"] = "+ints[i]); } – run, and see that ints is updated

Returning data Java – define function to return int public native int stringFromJNI(int[] val); – Call function and print return value Log.e("debug","results = "+stringFromJNI(ints)); C++ – Change function prototype to return jint JNIEXPORT jint JNICALL Java_edu_udel_eleg454_helloJni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz, jintArray jiArray ) – return int return 12; Build, compile, run

Return arrays Same as returning a string but use NewIntArray