简体   繁体   中英

JNA char** argument

I need to call a DLL function from java with a string array argument. The argument value has to be the same arguments passed to the java program from command line (main method argument). The function has following signature:

int calledFunction(char **args);

The main method argument is type is String[] and according to the JNA documentation , String[] should be directly equivalent to char ** .

But when I pass the argument from command line directly to the DLL, the program crashes or the DLL doesn't interpret the values correctly (the values don't make sense).

Any ideas?

JNA interface definition:

public interface TestDll extends Library {

    int calledFunction(String[] param);

}

Usage:

public static void main(String[] args) {
    TestDll testDll = Native.loadLibrary("test_dll", TestDll.class);
    testDll.calledFunction(args);
}

You should create a new array, bigger (by 2) than args

String[] new_str_array = new String[ args.length + 2 ] // +1 for program name, +1 for null
  • A regular C function managing the char **args of a main function, expect the first string to be the program name.
  • The array of pointer must be terminated by an extra null pointer

Then, you you should put the program name at the beginning

new_str_array[ 0 ] = "MyProgramExecutableName";

Then, copy the args passed to the Java program

for (int i = 0; i < args.length; i++) {
   new_str_array[ 1+i ] = args[ i ];
}

Then call the C function with new_str_array , the last string (at index args.length + 1 ) should have been correctly set to null (by the new instruction)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM