Hui's profileOn the wayPhotosBlogListsMore ![]() | Help |
|
12/14/2006 using JNI in LinuxI'm busy in a research report this week, a lot of programming work is needed. Here is the requirement: creage a data set follows exponetial distribution with a mean value mu, using this data set as parameters to run some existed progrmming in java. I found a GNU libraray called GSL to create this data set. Wow, it's another story about how to deploy it, however, most problems can be solved by the mannual, url: http://www.gnu.org/software/gsl/ Here is the introduction from this website: The (GSL) library provides a wide range of mathematical routines such as random number generators, special functions and least-squares fitting. There are over 1000 functions in total with an extensive test suite. Hope this may be helpful for those guys who have similar mathematical requirment. My problem is, since the library is c/c++ based, I have to write a c/c++ program to use it. However, it will be tedious to change my existing java code into c. So finally I have to face and solve the problem of calling a c progrm in java, Java Native Interface-JNI, which I'm afraid of touching before. Here I list the steps: 1. write a java program ("Node.java" for my example) that will call the c program, includes this code segements:
2. compile the "Node.java" file as usual: javac Node.java, then you'll get Node.class file. 3. "javah Node" to create a "Node.h" file, "-gni" is a default option for this command, so you don't have to "javah -gni Node" 4. Now, take a look at "Node.h", it's like this:
you see setence: JNIEXPORT jdouble JNICALL Java_Node_getData (JNIEnv *, jclass, jdouble); that's what we should implent in our c code! 5. Move to c code, here is my exmple "randGen.c":
I highlight the related jni setences in red: first, include the .h file; further, implent the function defined in the .h file, add some parameters to this function, remain other parts unchanged! Notice that i have some setences regarding GSL here. 6. gcc -shared -o randGen.so -lgsl -lgslcblas -lm words unline are required by GSL. -shared is a must option to get a ".so" file. Also, notice that here the "randGen" of "randGen.so" correspondes to System.loadLibrary("randGen"); in the java file.7. quite imporant and easy to ignore: add the location where you'd like to place the ".so" file in the environment variable "LD_LIBRARY_PATH", as for me, I include current directory: export LD_LIBRARY_PATH = $LD_LIBRARY_PATH:.
8. now, ready? run your java file! java Node, etc. for me. This is an exciting experience, I also wanna it unforgettable, that's why I blogged it here. enjoy it~. Thanks to Cong~ 12/9/2006 zz广埠屯街道口珞珈山发信人: cadaver (饭团), 信区: Feeling |
|
|