As of lately, I’ve been having fun with low-level programming, and have had to perform tasks like
- Implement high performance unbuffered disk access from Java/Kotlin (access to raw memory buffers required, but speed went from 2GB/s to 3.1GB/s in the fastest NVME SSDs)
- Calls to external OS DLLs with access to external memory buffers to work with Large Pages.
- Shared memory usage
I have needed to access memory directly from Java and Kotlin, and have had to wrap such access in the JVM side, and that has meant having to deal with pointers pointing to all kinds of data.
Unfortunately (or maybe fortunately, as it avoid lots of very troublesome problems) the JVM does not provide a way to manipulate pointers…except by using the
Unsafe class. That is not portable, but in reality there are so many projects using it to attain high performance, that it is present in all JVM I have ever used for production code.
So, we have
Unsafe, but…it sees pointers as
longs, and that is really bad when what you have are pointers to all kinds of data, need to perform pointer arithmetic, etc. So, to point to the to next
byte, increase the long/pointer by 1, but increase it by 4 if it is a
float, by 2 if it is a
char etc, etc. And don’t mix it, or you’ll get in deep trouble, as
Unsafe is much more dangerous for working with pointers than the way we work with pointers in C or C+++.
Now, the inherent risk of working with pointers that is one of the reason Java doesn’t support pointers, and we are all happy about it -most of the time.
But, if you need pointers, you need the safest possible pointers there are, not plain longs. So, if you are working with Kotlin, use KPointers: it provides high performance pointer types for all primitive types, and support all standard pointer operations, from pointer arithmetic to indexed access, increment, decrement, etc.
If you want to see code for that, go to the README page of KPointers: it is short and goes straight to the point