Is it possible to use JNA to get the signature of a function

Viewed 72

Is it possible to use JNA to check that the signature of the Java interface is consistent with the signature of the associated C funtions?

For example suppose that I have the following C interface for my C code:

__declspec(dllexport) void receive(bool boolValue, int intValue);

And the associated Java interface:

public interface MyLibrary extends Library {
  public void receive(int intValue, bool boolValue);
}

If I load the library, I will have no problem, but of course I will have an error if calling the receive method of the interface because the signature of the method is not aligned with the signature of the corresponding function.

Is there any way to know that the alignment is off before calling the method? I though about using:

Function function = NativeLibrary.getFunction("receive");

But after that it seems that I have no way to know anything about the signature of the function.

1 Answers

No, there is no automated mechanism, and in fact incorrectly mapping types is probably the most common error made when implementing JNA mappings, and that's usually the very first thing I check when code misbehaves.

If JNA can't find a matching function with the same number of arguments, you'll get an error:

java.lang.UnsatisfiedLinkError: Error looking up function 'Foo': The specified procedure could not be found.

If the method name matches the native function, and the number of arguments matches, JNA will not give any obvious indication of an improper mapping, however if you write robust unit tests and attempt to obtain sane/expected output from the native function, this will help catch most errors (although "catch" means "displays odd symptoms.")

You still may miss platform-dependent errors such as 32- vs. 64-bit long or pointer types.

There are still cases where it is technically impossible to know the correct mapping for a compiled library where the byte width of some types depends on compile-time switches, such as for the off_t type. There is no foolproof way of determining this at run time.

Related