java-native-access / java-native-access/jna
JNA should include std::exception::what() in thrown `java.lang.Error`
Nobody has claimed this yet.
- Dominant language
- Java
- Stars
- 8.9k
- Forks
- 1.7k
- PR merge metrics
- No merged PRs in 30d
Description
As a caller of a cpp hunk of math I want std::exceptions to be nicely translated by JNA across the bindings so that I can more easily debug runtime problems.
I have some cpp code that I've updated to throw std::exception's that contain valuable data in their what() clause. What I was hoping JNA would do is this:
//mylib.dll
#include <exception>
extern "C" __declspec(dllexport)
const void MYCOMPANY_compute_eigen_values_or_something()
{
throw std::exception("message from native code: kablamo!")
}
interface MyLib: Library {
public void MYCOMPANY_compute_eigen_values_or_something()
}
var lib = Native.loadLibrary("mylib", MyLib.class, options)
try { lib.MYCOMPANY_compute_eigen_values_or_something() }
catch(Throwable ex){
System.out.println(ex)
}
expected: java.lang.Error: In native code: message from native code: kablamo!
actual: java.lang.Error: Invalid memory access
... on: Windows 10 1903, JNA 4.2.2
My work around:
Wrap my code in a try { } catch { }, save it to a global variable, and expose a function GetLastError() that I then call from the handler. If you combine this with StackWalker you can even get a java--ish native code stack trace in your preconditions/postconditions. From the java side, I add my own InvocationMapper to catch JNA thrown java.lang.Errors, call GetLastError() then throw a new exception with the results.
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 at the Native.loadLibrary binding path and trace how a native std::exception becomes java.lang.Error. Compare that path with the issue's InvocationMapper and GetLastError workaround. Done means the thrown error includes std::exception::what() instead of only reporting invalid memory access, with the behavior checked against the Windows example.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp, java
- Domain
- backend, tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100