# HG changeset patch # User Markus Bröker # Date 1239878952 -7200 # Node ID 77094ec383cf0f31f2abdbc225d6eb1e2c6e87f4 # Parent b94d657a9acb54a0bdcd13c087b7fe596227a9af libConsole: a java native interface example * getch: unbuffered character input committer: Markus Bröker diff --git a/libConsole/Console.java b/libConsole/Console.java new file mode 100644 --- /dev/null +++ b/libConsole/Console.java @@ -0,0 +1,6 @@ +public class Console { + public static native int getch (); + static { + System.loadLibrary ("Console"); + } +} diff --git a/libConsole/Getch.java b/libConsole/Getch.java new file mode 100644 --- /dev/null +++ b/libConsole/Getch.java @@ -0,0 +1,20 @@ +import java.io.*; + +public class Getch { + public static void main (String args[]) { + int c; + + System.out.println ("Press q or ESCAPE to quit"); + for (;;) { + c = Console.getch (); + switch (c) { + case 27: + case 'q': + System.exit (0); + break; + default: + System.out.printf ("KEY: %c (%d)\n", c, c); + } + } + }; +}; diff --git a/libConsole/Makefile b/libConsole/Makefile new file mode 100644 --- /dev/null +++ b/libConsole/Makefile @@ -0,0 +1,47 @@ +CC=gcc +JAVA=java +JAVAH=javah +JAVAC=javac +LIB=lib/libConsole.so + +ifdef JAVA_HOME + JAVA_DIR="$(JAVA_HOME)" +else + JAVA_DIR=/usr/lib/jvm/java-6-sun +endif + +INCLUDE=-I$(JAVA_DIR)/include -I$(JAVA_DIR)/include/linux -Iinclude +SOURCES= \ + Getch.java \ + Console.java + +OBJECTS= \ + getch.o + +.SUFFIXES: .java + +.c.o: + @echo "JAVA_HOME=$(JAVA_DIR)" + $(CC) -c $(CFLAGS) $(INCLUDE) $< -o $@ + +all: Getch.class $(LIB) + +Getch.class: $(SOURCES) + $(JAVAC) -d . $(SOURCES) + $(JAVAH) -jni -d include Console + +$(LIB): $(OBJECTS) + $(CC) -shared -Wl,-soname,libConsole.so.1,-rpath,lib $(OBJECTS) -o $@ + +.PHONY: clean + +clean: + rm -f include/Getch.h include/Console.h *.class *~ $(LIB) + rm -f $(OBJECTS) + +debug: Getch.class lib/libConsole.so + LD_LIBRARY_PATH=lib $(JAVA) -cp . Getch + +run: Getch.class $(LIB) + @echo "You need to copy libConsole.(so|dll) to $(JAVA_DIR)/jre/lib/i386" + $(JAVA) -cp . Getch diff --git a/libConsole/getch.c b/libConsole/getch.c new file mode 100644 --- /dev/null +++ b/libConsole/getch.c @@ -0,0 +1,41 @@ +#include +#include +#include + +#ifdef WIN32 +#include + +int getch () +{ + int ch = -1; + + while (!kbhit ()) { + ch =::getch (); + } + + return ch; +} + +#else +#include + +int getch () +{ + int ch = -1, fd = 0; + struct termios neu, alt; + + fd = fileno (stdin); + tcgetattr (fd, &alt); + neu = alt; + neu.c_lflag &= ~(ICANON | ECHO); + tcsetattr (fd, TCSANOW, &neu); + ch = getchar (); + tcsetattr (fd, TCSANOW, &alt); + return ch; +} +#endif + +JNIEXPORT jint JNICALL Java_Console_getch (JNIEnv * env, jclass lass) +{ + return getch (); +} diff --git a/libConsole/include/.keep b/libConsole/include/.keep new file mode 100644 diff --git a/libConsole/lib/.keep b/libConsole/lib/.keep new file mode 100644