Search code examples
javajava-native-interfacefortranjna

Mapping custom types Fortran-to-Java (with JNA)


I have to write an interface of of Fortran subroutine to be called from Java. Some arguments in the Fortran subroutine are derived types (custom types / struct). Is it possible to map those with JNA? So far I cannot so how this could work. What about JNI?

e.g. a subroutine like this:

subroutine mysub(arg)
implicit none
type mytype
   integer:: i
   real*8 :: a(3)
end type mytype

type(mytype) arg

! do stuff...

end subroutine mysub

Solution

  • Yes, JNA supports aggregate types (struct in C) both by reference and by value. The default convention for arguments is by value, e.g.

    public interface MyLibrary extends Library {
        MyLibrary INSTANCE = (MyLibrary)Native.loadLibrary("mylib", MyLibrary.class);
    
        class MyStruct extends Structure {
            public static class ByValue extends MyStruct implements Structure.ByValue {}
            public int i;
            public double a[3];
            protected List getFieldOrder() {
                return Arrays.asList("i", "a");
            }
        }
    
        void mysub(MyStruct.ByValue arg);
    }