I Dream of JNI When it absolutely, positively has to be written in COBOL... shudder.

Slides:



Advertisements
Similar presentations
Objects and Classes David Walker CS 320. Advanced Languages advanced programming features –ML data types, exceptions, modules, objects, concurrency,...
Advertisements

Linking & Loading CS-502 Operating Systems
Computer Organization CS224 Fall 2012 Lesson 12. Synchronization  Two processors or threads sharing an area of memory l P1 writes, then P2 reads l Data.
Kernighan/Ritchie: Kelley/Pohl:
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
Client Side Programming Using Java Applet Outcomes: You will be expected to know: – Java Applets and HTML file; –bytecode and platform independent programs;
Java Native Interface Modified from CS587x Lecture Department of Computer Science Iowa State University.
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.
Principles of Object-Oriented Software Development The language Java.
Administrivia No class next Monday (May 2) Enjoy extra time on P3. ;-) Reading 3 available “Reflections on Trusting Trust”, Ken Thompson No written summary.
History  We first begin with Java which was released in 1995 by Sun Microsystems  Initially Java was 100% interpreted at runtime and was very slow 
Java 1.5 Features (1) Foreach and enums. Administrivia Labs Took feedback Consensus: Labs are valuable, but take a lot of time Result: We will continue.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
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.
Introduction to Java.
Lecture 1: Overview of Java. What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed.
Peter Juszczyk CS 492/493 - ISGS. // Is this C# or Java? class TestApp { static void Main() { int counter = 0; counter++; } } The answer is C# - In C#
Garbage Collection CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Java and C++, The Difference An introduction Unit - 00.
Java Native Interface CS587x Lecture Department of Computer Science Iowa State University.
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.
Object Oriented Programming: Java Edition By: Samuel Robinson.
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.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
University of Houston-Clear Lake Proprietary© 1997 Evolution of Programming Languages Basic cycle of improvement –Experience software difficulties –Theory.
The Java Programming Language
Thread-Safe Programming Living With Linux. Thread-Safe Programming Tommy Reynolds Fedora Documentation Project Steering Committee
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
© 2012 Pearson Education, Inc. All rights reserved. 1-1 Why Java? Needed program portability – Program written in a language that would run on various.
National Taiwan University Department of Computer Science and Information Engineering National Taiwan University Department of Computer Science and Information.
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)/
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
Writing a Run Time DLL The application loads the DLL using LoadLibrary() or LoadLibraryEx(). The standard search sequence is used by the operating system.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
VARIABLES Programmes work by manipulating data placed in memory. The data can be numbers, text, objects, pointers to other memory areas, and more besides.
JAVA COURSE 1 Computer Engineering Association. Compile your first program Public class Hello{ public class Hello(){ System.out.println(“Hello”); } puclic.
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Slide Advanced Programming 2004, based on LY Stefanus's slides Native Methods.
© 2012 Pearson Education, Inc. All rights reserved types of Java programs Application – Stand-alone program (run without a web browser) – Relaxed.
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Java Package Advantage of Java Package
Week 4 - Friday.  What did we talk about last time?  Some extra systems programming stuff  Scope.
Program Libraries 1. What is a program library? A library is a collection of implementations of behavior, written in terms of a language, that has a well-defined.
OOP Basics Classes & Methods (c) IDMS/SQL News
ENEE150 – 0102 ANDREW GOFFIN Abstract Data Types.
Creating Java Applications (Software Development Life Cycle) 1. specify the problem requirements - clarify 2. analyze the problem - Input? Processes? Output.
RealTimeSystems Lab Jong-Koo, Lim
JNI: Java Native Interface(1/32) Real Time Systems LAB. JNI: Java Native Interface October 31, 2001 Kyung-Yim, Kim.
Sung-Dong Kim, Dept. of Computer Engineering, Hansung University Java - Introduction.
Object Oriented Programming in
Lecture 1b- Introduction
Chapter 5: Enhancing Classes
Intro to Java L. Grewe.
The University of Adelaide, School of Computer Science
Linking & Loading.
CS-3013 Operating Systems C-term 2008
CMPE212 – Stuff… Assn 3 due and Quiz 2 in the lab next week.
Introduction to C# AKEEL AHMED.
Built-In (a.k.a. Native) Types in C++
Linking & Loading CS-502 Operating Systems
Linking & Loading CS-502 Operating Systems
Concurrency, Processes and Threads
The Three Attributes of an Identifier
Presentation transcript:

I Dream of JNI When it absolutely, positively has to be written in COBOL... shudder

Administrivia P3 milestone grades back today R2 back today R3 For fun -- no hand-in required “The Story of Mel, a Real Programmer”

Quote of the day Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- B. Kernighan

Quote of the day Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- B. Kernighan I would add that maintaining code over long period of time is twice harder than debugging it. -- J. Tourrilhes

Flashback: Enums Open questions on Java 1.5 enums: Are they extensible if you don’t add functionality? Can you import enum symbols? What does it mean for enum to be static? Can an “inner enum” access its outer class’s stuff?

Flashback: Enums Open questions on Java 1.5 enums: Are they extensible if you don’t add functionality? No. Enums appear to be non-extensible period. Can you import enum symbols? What does it mean for enum to be static? Can an “inner enum” access its outer class’s stuff?

Flashback: Enums Open questions on Java 1.5 enums: Are they extensible if you don’t add functionality? No. Enums appear to be non-extensible period. Can you import enum symbols? Yes! (yay) What does it mean for enum to be static? Can an “inner enum” access its outer class’s stuff?

Importable enums public enum FruitEnum { RASPBERRY, CHERRY, APPLE, GRAPE; } // in another class file import static long.pkg.specifier.FruitEnum.*; public class EnumDemo { public static void main(String[] args) { out.println(FruitEnum.CHERRY); out.println(GRAPE); }

Flashback: Enums Open questions on Java 1.5 enums: Are they extensible if you don’t add functionality? No. Enums appear to be non-extensible period. Can you import enum symbols? Yes! (yay) What does it mean for enum to be static? Nothing (AFAICT). All enums appear to be implicitly static. Can an “inner enum” access its outer class’s stuff?

Flashback: Enums Open questions on Java 1.5 enums: Are they extensible if you don’t add functionality? No. Enums appear to be non-extensible period. Can you import enum symbols? Yes! (yay) What does it mean for enum to be static? Nothing (AFAICT). All enums appear to be implicitly static. Can an “inner enum” access its outer class’s stuff? No, b/c they’re all effectively static anyway

I dream of JNI but it’s a nightmare.

Gospel according to K&R In The Beginning, Kernighan said unto Ritchie, “Let us create C in the image of B, after our own whims. And let it have dominion over the I and the O and all the data that runneth upon the bus.” And it was almost, but not quite so. And Kernighan saw that he had his work cut out for him...

The joy of JNI Caveat: This is version 1.4 JNI May be diff for 1.5 (haven’t tested yet) “Java Native code Interface” When you really, truly, absolutely need to talk to C Interface to existing libraries OS system calls not available in Java ioctl, fcntl, symlink, etc. Performance tuning/critical sections (Danger!!!) JNI allows Java to call C functions and vice- versa Specific to a single JVM

Dangers of JNI Data in C memory space not garbage collectable C does no garbage collection natively ⇒ doesn’t know to notify JVM’s GC about data structs Can get a Java data struct and “pin it down” indefinitely Data in C space not relocatable Can’t resize ArrayList, etc. while C has it C code not portable C code really, really not OO Can easily corrupt Java data structs from C Much harder to be threaded Have to work hard to “play nice”

Building a JNI application 1. Write Java code first 2. Create “stub” methods for C function names Mark w/ Java native keyword 3. Use static code block to load C shared library 4. Compile Java 5. Extract C header info from.class file w/ javah prog 6. Write C function to header spec 7. Compile C function to shared library (DLL) 8. Run Java program 9. Relax w/ margarita

Building a JNI application 1. Write Java code first 2. Create “stub” methods for C function names Mark w/ Java native keyword 3. Use static code block to load C shared library 4. Compile Java 5. Extract C header info from.class file w/ javah prog 6. Write C function to header spec 7. Compile C function to shared library (DLL) 8. Run Java program 9. Relax w/ margarita (or debug and grumble)

Native methods native keyword is Java method signature marker Similar to abstract -- tells Java that you’re not providing a function body Unlike abstract, class will still compile Java assumes it’s not responsible -- function defined elsewhere native funcs can be public / protected / private, static /non- static, any args/return type Not sure about synchronized

Extracting a C header Java expects native function to translate to a specific C function name/signature Use javah tool to get header info from.class file javah -jni MyClass Produces MyClass.h

Extracting a C header Java expects native function to translate to a specific C function name/signature Use javah tool to get header info from.class file javah -jni MyClass Produces MyClass.h // in Java public native static void doit(); /* in C */ JNIEXPORT void JNICALL Java_SimpleJNI_doit (JNIEnv *, jclass);

Writing the C code In C code: #include Use same function signature that MyClass.h specifies Note! If you change native func declaration in Java → change header file → change C file. Beware! Access Java data via args to func Can provide additional C funcs, C local data, etc.

Making a shared library A.k.a., dynamically loadable library (DLL) On linux/UNIX: libMyLibName.so On Windows: MyLibName.dll On Mac OSX: libMyLibName.dylib (???) Creating them diff for each platform/compiler (ugh) Linux: gcc -shared -fPIC -DPIC -fno-exceptions Windows: ??? Mac OSX: gcc -dynamiclib Have to make sure dynamic loader search path is right

Accessing Java data Java.class →.h provides extra args to func signature JNIEnv *envPtr -- pseudo-“class”: provides Java utility functions Data allocation/deallocation, access/release, etc. jclass classPtr -- ptr to class of object that called native method (static case) jobject objPtr -- “this” -- ptr to object that called native method (non-static case) Other args/return vals are Java method args

Accessing Java data, II Atomic types (int, char, float, etc.) directly accessible Declared jint, jchar, jfloat, etc. Anything more complex requires hoops... jstring sArg; char *cStr= (char*)(*envPtr)->GetStringUTFChars(envPtr,sArg,0); /* do stuff with cStr */ (*envPtr)->ReleaseStringUTFChars(envPtr,sArg,str);

Accessing Java data, III GetStringUTFChars() tells Java “C has a pointer to this; don’t garbage collect it and don’t move it”. Have to explicitly release with ReleaseStringUTFChars Same rule for any Get*() / Release*() functions Good rule of thumb: Call Get*() when enter function/block and Release*() when leaving it Similar functions for calling methods, accessing object local data/fields, etc.