使用 long 将指针从 JNI 传递到 Java

我正在尝试将结构作为指针从 JNI 传递到 Java,以便以后能够将其从 Java 传递回 JNI.我已阅读此主题:通过 JNI 在 C 和 Java 之间传递指针,但我没有成功.

I'm trying to pass a structure as a pointer from JNI to Java to be able to pass it back later from Java to JNI. I have read this thread: Passing pointers between C and Java through JNI, but I did not succeed.

我有一个相当复杂的结构:struct myStruct_s myStruct;

I have a pretty complex structure : struct myStruct_s myStruct;

在 Java 中,我调用一个 JNI 函数来初始化结构并返回一个 long(指向结构的指针):

From Java, I call a JNI function to initialize the structure and to return a long (pointer to the structure):

JNIEXPORT jlong JNICALL Java_example_ExampleJNI_getStruct(JNIEnv *jenv, jclass jcls) {
    struct myStruct_s mystruct;
    long *lp = (long*)&myStruct;
    return lp;
}

然后我用那个长的参数调用一个 Java 方法.在 JNI 中,我希望能够使用之前创建的结构.我喜欢这样:

Then I call a Java method with that long in argument. In JNI I want to be able to use the strcuture created earlier. I do like this:

JNIEEXPORT jint JNICALL Java_example_ExampleJNI_methode1(JNIEnv *jenv, jclass jcls, jlong jarg) {
    struct myStruct_s *arg = (struct myStruct_s *)&jarg;
    ...
}

好吧,它不起作用.我猜我对结构的长期转换是错误的.我该怎么做?谢谢.

Well it doesn't work. I guess my cast of the long into the struct is wrong. How should I do it? Thank you.

编辑:感谢您的提示,这里是工作功能

EDIT : Thanks for the hints, here are the working functions

JNIEXPORT jint JNICALL Java_example_ExampleJNI_methode1(JNIEnv *jenv, jclass jcls, jlong jarg) {
    struct myStruct_s *arg;
    arg = (struct myStruct_s *)jarg;
    ...
} 

JNIEXPORT jlong JNICALL Java_example_ExampleJNI_getStruct(JNIEnv *jenv, jclass jcls) {
    struct myStruct_s *myStruct;
    myStruct = (struct myStruct_s *)malloc(sizeof(struct myStruct_s));
    long lp = (long)myStruct;
    return lp;
}

推荐答案

在你的例子中

struct myStruct_s mystruct;

是堆栈上的局部变量,因此在函数返回后不可用.可能这只是您的代码的缩减,但如果没有,则使用 malloc(sizeof(struct myStruct_s)) 为自己分配堆.

is a local variable on the stack, and therefore not available after the function returns. Possubly that's just a cut-down of your code, but if not then use a malloc(sizeof(struct myStruct_s)) to get yourself a heap allocation.

然后提出了一个问题,即何时释放该分配,注意内存泄漏.

That then raises the question of when you are going to free that allocation, watch out for memory leaks.

相关文章