How to pass C structure in java using JNI?

From C I am creating a DLL loaded in Java. I call some C functions from java, and also call Java functions from C (with non-complex data types) - this works fine.

I am struggling with porting the C structure to Java.

Here is a small example of a description of what I want to do. This is not complete and possibly incorrect, because my problem is that I am not sure how to do this.

My goal is to pass a structure from type "StructType" from C to Java to use the values ​​in a Java program.

In C

typedef struct { unsigned char value1; unsigned char value2; } StructType; void passStructToJava(StructType* myStruct) { class cls; jmethodID mid; /* GlobalEnv, GlobalObj are globlal values which are already set */ cls = (*GlobalEnv)->GetObjectClass(GlobalEnv, GlobalObj); mid = (*GlobalEnv)->GetMethodID(GlobalEnv, cls, "receiveStructFromC", "(LPackage/StructType;)V"); (*GlobalEnv)->CallVoidMethod(GlobalEnv, GlobalObj, mid, myStruct); } 

In java

  public class StructType { public int value1; /* int because there is no uint8 type */ public int value2; } public StructType mMyStruct; public StructType getMyStruct() { return mMyStruct; } public void setMyStruct(StructType myStruct) { mMyStruct = myStruct; } public void receiveStructFromC(StructType myStruct) { setMyStruct(myStruct); } 

Thanks in advance for your help. Steffen

+6
java c data-structures jni
source share
2 answers

Mark my post on this question: pass data between Java and C

+1
source share

I would suggest returning an int array, since your structure does not contain anything else.

As for returning an object: you can create an object of your StructType class, fill the values ​​with setters and return it.

The necessary code samples can be found here .

Just an example, I did not check this code.

 returnObj = (*env)->AllocObject(env, objClass); if (returnObj == 0) printf("NULL RETURNED in AllocObject()\n"); printf("Sizeof returnObj = %d\n", sizeof(returnObj) ); (*env)->SetObjectField (env, returnObj, fid5, combinedEmployeeNameJava); (*env)->SetIntField (env, returnObj, fid6, combinedSalary); 
0
source share

All Articles