JNA char** 参数
JNA char** argument
我需要使用字符串数组参数从 java 调用 DLL 函数。参数值必须与从命令行(主方法参数)传递给 java 程序的参数相同。该函数具有以下签名:
int calledFunction(char **args);
主要方法参数的类型是String[]
,根据JNA documentation,String[]
应该直接等同于char **
。
但是当我将参数从命令行直接传递给 DLL 时,程序崩溃或 DLL 无法正确解释这些值(这些值没有意义)。
有什么想法吗?
JNA 接口定义:
public interface TestDll extends Library {
int calledFunction(String[] param);
}
用法:
public static void main(String[] args) {
TestDll testDll = Native.loadLibrary("test_dll", TestDll.class);
testDll.calledFunction(args);
}
您应该创建一个新数组,比 args
大(2 倍)
String[] new_str_array = new String[ args.length + 2 ] // +1 for program name, +1 for null
- 管理 main 函数的 char **args 的常规 C 函数,期望第一个字符串是程序名称。
- 指针数组必须由一个额外的空指针终止
那你把程序名放在最前面
new_str_array[ 0 ] = "MyProgramExecutableName";
然后,复制传递给 Java 程序的参数
for (int i = 0; i < args.length; i++) {
new_str_array[ 1+i ] = args[ i ];
}
然后使用 new_str_array
调用 C 函数,最后一个 string
(在索引 args.length + 1
处)应该已正确设置为 null
(由 new
说明)
我需要使用字符串数组参数从 java 调用 DLL 函数。参数值必须与从命令行(主方法参数)传递给 java 程序的参数相同。该函数具有以下签名:
int calledFunction(char **args);
主要方法参数的类型是String[]
,根据JNA documentation,String[]
应该直接等同于char **
。
但是当我将参数从命令行直接传递给 DLL 时,程序崩溃或 DLL 无法正确解释这些值(这些值没有意义)。
有什么想法吗?
JNA 接口定义:
public interface TestDll extends Library {
int calledFunction(String[] param);
}
用法:
public static void main(String[] args) {
TestDll testDll = Native.loadLibrary("test_dll", TestDll.class);
testDll.calledFunction(args);
}
您应该创建一个新数组,比 args
String[] new_str_array = new String[ args.length + 2 ] // +1 for program name, +1 for null
- 管理 main 函数的 char **args 的常规 C 函数,期望第一个字符串是程序名称。
- 指针数组必须由一个额外的空指针终止
那你把程序名放在最前面
new_str_array[ 0 ] = "MyProgramExecutableName";
然后,复制传递给 Java 程序的参数
for (int i = 0; i < args.length; i++) {
new_str_array[ 1+i ] = args[ i ];
}
然后使用 new_str_array
调用 C 函数,最后一个 string
(在索引 args.length + 1
处)应该已正确设置为 null
(由 new
说明)