Although the accepted answer from @ denis-tulskiy makes sense, I personally followed the suggestions here .
Therefore, instead of using a pseudo-pointer type such as jlong (or jint if you want to save some space on a 32-bit arch), use ByteBuffer instead. For example:
MyNativeStruct* data; // Initialized elsewhere. jobject bb = (*env)->NewDirectByteBuffer(env, (void*) data, sizeof(MyNativeStruct));
which can later be reused:
jobject bb; // Initialized elsewhere. MyNativeStruct* data = (MyNativeStruct*) (*env)->GetDirectBufferAddress(env, bb);
For very simple cases, this solution is very easy to use. Suppose you have:
struct { int exampleInt; short exampleShort; } MyNativeStruct;
On the Java side, you just need to do:
public int getExampleInt() { return bb.getInt(0); } public short getExampleShort() { return bb.getShort(4); }
This saves you from writing a lot of templates! However, attention should be paid to the byte order as described here .
malat Apr 17 '15 at 9:38 2015-04-17 09:38
source share