I built my jar file and shared objects relatively easily. Next I tried running the jar file. The jar file linked to my shared object ok, but it couldn't find the function being called. I kept getting an UnsatisfiedLinkError. I guessed the reason was due to C++ name mangling.
Javah is used to create the jni header files. When the header files are created, javah automatically adds:
#ifdef __cplusplus
extern "C" {
#endif
to prevent C++ from mangling function names. I believe the command I used to look at the function names in the shared object was nm. Weird thing is, the names kind of looked mangled. I did some research on the internet, but found nothing useful. Everything worked fine on Windows, the header files use #ifdef cplusplus to prevent name mangling, so how could the function names be mangled? I don't know. I was desperate, so took the #ifdef cplusplus and put it in the C++ source file too. Right at the top, after the includes and before the first function. I ended the #ifdef cplusplus at the very end of the file. I recompiled and tried running the jar file again. What do you know? No more UnsatisfiedLinkErrors. The jar file found the functions in the shared object just fine. Thank goodness.
Got your anser!
ReplyDeleteAdd #include "lib.h" to your lib.cpp file (supposing your native lib is called lib!)