简体   繁体   中英

Copying Data from Java to C++ Objects Array Using JNI

I have Java code that requires heavy calculations which I would like to forward into C++ using JNI.
My main concern is having all the data serialized in memory, and next to forward the computation to GPU.
Since the data is received in Java, but the main calculations are done using C++, I thought of arranging all the data continuously in a raw array ( ByteBuffer or raw bytes from Unsafe ), in the same structure as the C++ object.
For example, suppose I have a point with x and y . In C++ the object has a size of 24 bytes. 8 bytes for (I guess) VTable, 8 bytes for x and 8 bytes for y .
So in Java, I would arrange all the data in the same structure and pass the buffer to C++ using JNI, and in C++ cast it to an array of points.

This worked fine, and I am allowing myself to assume that I will always use the same C++ compiler, same JDK, same OS and same HW (at least for testing the feasibility of the solution).

My question is if these assumptions are correct, or there is a better way to pass serialized data between Java and C++ (I must use JNI and not some kind of IPC)?

if I can rely on the C++ structure (offset, alignment of the fields, etc.)

No, unless you know what your compiler on your specific platform will do in that case. It yields undefined behavior.

Aliasing the content of ByteBuffer (aka char * ) with Point * to later access its members is not possible in idiomatic C. Take a look at the C Standard N1570 6.5 (p7) :

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:88)

— a type compatible with the effective type of the object,

Assuming you know that void * returned by GetDirectBufferAddress is itself returned by a call to malloc(size) or friends (it actually uses malloc ) where size_t size = sizeof(struct Point) than you can cast it to Point * initialize its member from native code and later use it. That would be a conforming way (one of).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM