JNI 如何传递 C 结构体(连续内存) 给 dll的函数

我通过JNI 调用 dll 文件。
我知道通过JNI 可以让 c/c++直接访问java数据,但有些 dll 的接口需要传递结构体指针,比如:

typdef struct Student {
    char name[32];
    int age;
} Student;

void add_student(Student* stu);

我知道用JNI 将这个dll 包装一下,在封装库内的函数中,创建一个临时 Student 对象,再将Java数据复制过去,然后用这个临时对象地址调用 dll 接口 add_student(Student* stu)。大概这样:

    Student stu;
    strcpy(stu.name, xxx);
    stu.age = xxxx;
    add_student(&stu);

但这样就多了一步复制数据的操作。
如何能在 Java 代码中就创建 Student 这个对象(或者说内存),在JNI 的封装里,就可以直接获取地址,调用函数 add_student() ,直接操作这个对象,省去了数据复制的动作。
比如在Python 中可以用ctyps 直接创建结构体对象,可以直接传递给 dll 使用

from ctypes import *

class Student(Structure):  
    _fields_ = [
        ("name", (c_char*32)),
        ("age", c_int),
    ]

stu = Student()  // 创建一个结构体,内存结构与c中一样
dll = CDLL("mydll.dll")
dll.add_student(byref(stu)) # 可直接传地址给 c 函数使用

Java中要怎么样做呢?

解决了,使用 Native.malloc() 开辟内存,把返回的地址传给函数即可。

  • 关于该问题,我找了一篇非常好的博客,你可以看看是否有帮助,链接:JNI 调用 DLL