java - 如何使用 JNA 将 com.sun.jna.Structure 从 Java 传递到 C 中的结构

标签 java android android-ndk java-native-interface jna

我要离开 this如何传递 com.sun.jna.Structure 的示例包含 com.sun.jna.StringArray使用 JNA 从 Java 转换为 native C 代码,并且在 C 代码中无法成功获取 Structure 内容。

请注意,我可以成功地将结构从 C 代码传递到 Java 中的结构,但在 Java 代码中创建结构并将其作为结构成功发送到 C 代码时遇到问题。

这是有问题的代码:

String[] user_name_array = new String[3];
user_name_array[0] = "test_user_1";
user_name_array[1] = "test_user_2";
user_name_array[2] = "test_user_3";
StringList.ByReference members = new StringList.ByReference();
members.length = 3;
members.strings = new StringArray(user_name_array);
MyNativeLibrary.myMethod(members);

看起来很简单,但它不起作用。

按照预期成功进入C代码,但是Structure中的Pointer为空,长度为零。

这是Java中的StringList结构:

public static class StringList extends Structure {
    public volatile long length;
    public volatile Pointer strings;
    public static class ByValue extends StringList implements Structure.ByValue {}
    public static class ByReference extends StringList implements Structure.ByReference {
        public ByReference() { }
        public ByReference(Pointer p) { super(p); read(); }
    }
    public StringList() { }
    public StringList(Pointer p) { super(p); read(); }
}

以下是 C 代码中相应的结构体:

typedef struct string_list {
    uint64_t length;
    const char **strings;
} string_list;

这是 C 代码中的方法定义:

const char* my_method(struct string_list *members)
{
   //.................
}

使用 ndk-gdb,并进入这个函数,它显示如下:

(gdb) break my_method
(gdb) cont 
Continuing.

Breakpoint 1, my_method (members=0x9bee77b0) at ../app/my_code_file.c:368
(gdb) p *members
$1 = {length = 0, strings = 0x0}

看起来应该可以工作,那么为什么这些值没有进入 C 代码呢?我错过了什么?

另请注意,如果 StringArray 不在结构内部,我可以成功地将 StringArray 直接从 Java 代码发送到 C 代码:

Java:

//This works!
StringList members = MyNativeLib.myTestFunction(3, new StringArray(user_name_array));

C:

//This works!
string_list* my_test_function(uint64_t length, const char **strings)
{
    //......
}

在这种情况下,JNA 似乎按预期工作。那么,为什么它不能与结构一起使用 as the documentation states it should

最佳答案

不要将字段标记为 volatile 。当您这样做时,JNA 不会写入它们,除非您执行显式 Structure.writeField()。

关于java - 如何使用 JNA 将 com.sun.jna.Structure 从 Java 传递到 C 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36636186/

相关文章:

android - GLES 错误 : vertex attribute array is enabled with no data bound

java - mvn 编译 : Unable to find package java. lang

android - 如何确保当前在前台的任何应用程序 Activity 都能收到消息

android - 是什么导致android异常 "You need to use a Theme.AppCompat theme (or descendant) with this activity."

使用 Bambuser 源代码构建 Android-NDK

带有 Linux : "ndk-build" command not found 的 Android NDK

java - import com.google 无法解决?

java - 如何使用 spring data Criteria 构建器组合 "not"运算符

java - 如何捕获 java.sql.SQLIntegrityConstraintViolationException?

android - 如何在 Android 中仅获取 TTS 区域设置