Cuda library embedding in java with jni

Hey guys,

is it possible to generate a library of my Cuda code and to embed it with Java Native Interface in my Java Code?

Thanks for answers.


Yes, I’ve done that at work with a project and it works. We have a very large existing Java modeling code, it spends most of its cpu time doing FFTs. They didn’t want to have to redo the whole thing as C/C++ to use CUDA but just use JNI to do the calls for the FFT calculation, then keep the higher logical stuff in Java as is. It originally used the JMSL ComplexFFT and Complex packages to do the FFTs, so I made a Java/JNI/CUDA package so that if the code finds itself on a host with a CUDA library and video card it uses the JNI/CUDA FFTs via CUFFT else it uses JMSL as a fallback.

The tricky bit was getting all the arcane stuff in the JNI Makefile right to use gcc and nvcc in the right way so the JNI shared object is created. The JNI/CUDA package loads that via “loadLibrary()” to get access to the JNI functions.

Some gotcha’s:

avoid underscores in your JNI native function names, JNI uses underscores to separate the package name from the function name and if you have your own _ in there it gets confused.

use extern “C” in the “.cu” file for the JNI CUDA functions so the names don’t get mangled, if you don’t the cuda functions won’t link right.