class Greeting { public static native String sayHello(String name); static { System.loadLibrary("Greeting"); } }
javac Greeting.java javah Greeting
#include "Greeting.h" #include #include JNIEXPORT jstring JNICALL Java_Greeting_sayHello (JNIEnv *env, jclass cl, jstring name) { jstring jstr; char greeting[] = "Hello, "; char* cname; cname = (*env)->GetStringUTFChars(env, name, NULL); strcat(greeting,cname); jstr = (*env)->NewStringUTF(env, greeting); return jstr; }
//on Cygwin programming environment in windows gcc -mno-cygwin -D __int64="long long" -I JAVA_HOME/include/ -I JAVA_HOME/include/win32 -shared -Wl,--add-stdcall-alias -o Greeting.dll Greeting.c // Gnu C compiler on Linux gcc -fPIC -I JAVA_HOME/include -I JAVA_HOME/include/linux -shared -o libGreeting.so Greeting.c //With tSun compiler under the Solaris Operating System cc -G -I JAVA_HOME/include -I JAVA_HOME/include/solaris -o libGreeting.so Greeting.c //in Microsoft C++ compiler on Windows cl -I JAVA_HOME\include -I JAVA_HOME\include\win32 -LD Greeting.c -FeGreeting.dll
class GreetingTest { public static void main(String[] args) { System.out.println(Greeting.sayHello("Rukshan")); } }
javac GreetingTest.java java GreetingTest
Add Comment
Comments (1)
Very useful, thanks.