Search code examples
javadlljava-native-interfacenative-code

Call native function in DLL from java code. Sometimes throwing uncaught runtime exception


There is function written in DLL which is called by my java code. The function is declare as native in java. say the function has 3 arguments. when I use the function in java code with two arguments it works fine. But when I call the native function with three arguments it gives following error.

runtime exception : uncaught runtime exception.

Native method is overridden that means it can be called with any number of arguments. All the arguments are string type. So when the method is called with two arguments it always works. But if we called with 3 arguments. It works for the first 2-3 times then it throws runtime exception.

So I just wanted to know is this problem related with the function that is implemented in DLL or it's the problem in my java code. I've called the native function in Thread and this native function is using external windows resource. Because it works sometime I'm thinking that the thread is not properly working. Please suggest.

Example Code:

Java Code for Native function declaration:

System.LoadLibrary("demo") // demo is .dll which contains native function implementation. fn_dmeo(string 1, string 2); fn_demo(string 1, string 2, string 3); // this function opens notepad

Implementation for fn_demo is written in dll. So I'm calling fn_demo("","abc","xyz") in Thread.run() With two arguments and first one blank it always works.

If I do this fn_demo("pqr","abc","xyz"). Sometimes it works sometime it throws runtime exception.

why?


Solution

  • This issue was related to Memory Leak. Some of the variables in the dll code were not assigned to value properly and they were having Garbage value. Due to which the code was failing intermittently.