4 ms·
Not directly related to the artcile,but is there any article that explain how memory management (stack/heap) work when using FFI in java. Also when a call is ma
by creativeSlumber 2y ago
Not directly related to the artcile,but is there any article that explain how memory management (stack/heap) work when using FFI in java. Also when a call is made though FFI to a C library, is there a separate java and C call stack? I haven't found a good article yet on what happens under the hood.
- dzaima 2y agoDon't have an article, but the gist on stacks is that Java still uses the regular architecture stack (rsp on x86, etc) that the FFI'd code will, and on exit to/entry from FFI it'd have to store its stack end/start pointer (or otherwise be able to figure the range out) such that GC knows what to scan.
- kgeist 2y agoI wonder how it works when you use virtual threads. In Go, goroutines have resizable stacks which notoriously complicates FFI because C has no idea about resizable stacks (IIRC they have to temporarily switch to a separate, special C stack).
- mike_hearn 2y agoWhen it's running a virtual thread is using a physical OS level thread, and if you call into C then that virtual thread won't suspend. It pins the OS thread. So it's all transparent.
- w10-1 2y agoFor the heap, JEP 454 is reasonably detailed: https://openjdk.org/jeps/454 https://openjdk.org/jeps/454 It describes how to adopt memory from C and have C adopt memory you allocate, and gives control over how memory is allocated in an arena. The arena has lifecycle boundaries, and allocations determine the memory space available. Java guarantees (only) that you can't use unallocated memory or memory outside the arena, and if you access via a (correct) value layout, you should be able to navigate structure correctly. The interesting stuff is passing function pointers back and forth - look for `downcall method handles`.