JavaXT
|
|
How to Create a JNI with NetbeansNetbeans supports C and C++ programming languages using an optional C/C++ Plugin. The plugin currently supports two different C/C++ compilers for Windows: cygwin and minGW. In this tutorial, I will outline the the steps I took to compile and build a 32 bit JNI for Windows using minGW.Step 1: Download and Install minGWUnfortunately, the C/C++ plugin for Netbeans does not ship with a compiler. You will need to download and install mingw. I used an automated installer called mingw-get:Step 2: Create a C++ Dynamic Library ProjectOnce you have downloaded and installed minGW, you are ready to create a C++ project. Open Netbeans and go to File->New Project... Since we are creating a JNI, select "C++ Dynamic Library". Example:Step 3: Add Java IncludesOnce you have created your project, you will need to add references to Java. Go to Project Properties -> C++ Compiler Options. Add paths to the "jdk/include" and "jdk/include/win32" directories.Step 4: Add Compiler OptionsGo to Project Properties -> C++ Compiler Options. In the "Additional Properties" add "-shared -m32 -Wl,--add-stdcall-alias". Note that the resultant dll will have dependencies on gcc and stdc++. You can remove these dependancies with the following compiler flags: "-static-libgcc -static-libstdc++". This will increase the size of your dll by approx 1MB.Step 5: Create a java class with "native" methodsHere's a simple example from the javaxt-core JNI:final class FileAttributes { public static native long[] GetFileAttributesEx(String lpPathName) throws Exception; } Step 6: Create a .h file using javahCompile the class using javac and create a .h file with javah. Alternatively, you can point javah to your Netbeans build directory like this: javah.exe -o "FileAttributes.h" -classpath "C:\My Netbeans Project\build\classes" "FileAttributes" This will create a .h file called "FileAttributes.h" that will look something like this: /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class FileAttributes */ #ifndef _Included_FileAttributes #define _Included_FileAttributes #ifdef __cplusplus extern "C" { #endif /* * Class: FileAttributes * Method: GetFileAttributesEx * Signature: (Ljava/lang/String;)[J */ JNIEXPORT jlongArray JNICALL Java_FileAttributes_GetFileAttributesEx (JNIEnv *, jclass, jstring); #ifdef __cplusplus } #endif #endif Step 7: Add the .h file to your project and create a .cpp fileNext step is to implement the "native" JNI methods. To do so, add the newly created "FileAttributes.h" file to your project and create a "FileAttributes.cpp" file. Step 8: Compile and Build the DLLOnce you've implemented the methods in your .h file, compile and build your DLL. Make sure your configuration is set to Release Mode. Step 9: Implement Java-Side CodeLast step is to implement Java code to call the native method. Runtime Errors
References |