java-native-access / java-native-access/jna
Passing same buffer as two method arguments does not read back modified content
Nobody has claimed this yet.
- Dominant language
- Java
- Stars
- 8.9k
- Forks
- 1.7k
- PR merge metrics
- No merged PRs in 30d
Description
Assume the following native library function, which reads from in and writes to out:
int do_something(void *out, void *in);
mapped to the following interface in Jave:
public interface mylibrary extends Library {
public int do_something(ByteBuffer out, ByteBuffer in);
}
When calling this function with the same buffer backed by a heap-allocated array as both output and input argument, i.e.:
public void process(ByteBuf buffer) {
// buffer is backed by heap-allocated array
mylibraryInstance.do_something(buffer, buffer);
}
then the buffer will not be updated to reflect the content that was written to out within the native function implementation.
I assume this is because each argument will be processed individually, the buffer will be copied two times into native memory, both instances will be read back after the function call and the second argument (in, unmodified) replaces the first argument (out, modified & expected content).
Workaround: Create a new buffer before calling the native function (and write it back afterwards):
public void process(ByteBuf buffer) {
ByteBuffer outputBuffer = ByteBuffer.allocate(buffer.remaining());
outputBuffer.limit(buffer.remaining());
mylibraryInstance.do_something(outputBuffer, buffer);
// here, outputBuffer has the expected (modified) content - write back to original buffer
}
Version of JNA and related jars: jna 5.5.0 and jna-platform 5.5.0
Version and vendor of the java virtual machine: Oracle JDK 12.0.2
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the JNA call path for the do_something(ByteBuffer out, ByteBuffer in) entry point and the handling of heap-backed ByteBuffer arguments. Reproduce the call with the same buffer passed for both parameters on JNA 5.5.0, then verify that the modified output remains visible after the native function returns.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100