JNA Exceptions

I have a quick question about eliminating exceptions that cause libraries under JNA ...

When I throw an exception in the base code, JNA gets an invalid memory access error. I assume this is because C libraries cannot throw an exception through the stack (in fact, this is C ++ / CLR, but has C-export)? So is there a real way to report an exception from Java? Or โ€œshould this work,โ€ and I'm just doing something incredibly wrong?

DllExport void Initialize(char* dir) { throw gcnew System::Exception("Testing"); } 

It would be nice if Java could detect these abandoned exceptions, and I guess I could really consider passing a memory pointer to my entire C export and check if they are null or not, but it seems to be a roundabout way.

+6
source share
2 answers

You need to handle the C ++ exception yourself and instead create a Java exception that can be passed on the java side of the code.

+4
source

C ++ exceptions can only be handled in C ++ code. They will never be able to escape the C ++ world (i.e., the C ++ C code interface should never allow the distribution of exceptions). It is possible that a C ++ exception is propagated through a C code layer between two C ++ modules (for example, when a C ++ function calls a C function, which in turn calls a C ++ function).

One of the reasons for this is that there is no standard on how C ++ exception should be implemented, so C ++ modules are only binary compatible if they are compiled by the same compiler (in the same version). Therefore, code in any other language cannot be configured to handle C ++ exceptions.

In this case (the C ++ library, the C interface, is called from Java) you have to catch the C ++ exception, distribute the information through the C interface (for example, using error return codes), check it in Java and throw an exception there.

+4
source

Source: https://habr.com/ru/post/896128/


All Articles