7

From C I am creating a DLL which is loaded in Java. I call some C functions from java and also call Java functions from C (whith uncomplex data types) - this is working fine.

I struggle with the transfer of a C structure to Java.

Here is a small example descriping what I want to do. It is not complete and maybe not correct because my problem is that I am not sure how to do it.

My goal is to pass a structure from the type "StructType" from C to Java in order to use the values in the 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

Steffen Kuehn
  • 71
  • 1
  • 1
  • 2

2 Answers2

2

Check my post in this question: pass data between Java and C

Community
  • 1
  • 1
dacwe
  • 43,066
  • 12
  • 116
  • 140
0

I would suggest returning an int array, as far as your structure doesn't consist anything else.

As for returning the 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 the example, I haven't 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);
Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
  • Thanks Vladimir. The structure is a bit more complex as in the example and I need to use it. But how can I access the java object from the structure in the C function to use the setters and getters (following the example)? – Steffen Kuehn Jan 11 '11 at 10:43