Quantcast
Channel: Intel® Fortran Compiler for Linux* and macOS*
Viewing all articles
Browse latest Browse all 2583

Returning string to Java from Fortran using JNA

$
0
0

I've done a lot of trial-and-error, a lot of Googling, and yet can't get this to work.

I'm simply trying to have a fortran sub return an arbitrary string to a Java method using JNA. I'm using subroutines rather than functions because I would like to extend the idea to return a number of values.

Here's my latest fortran attempt:
   

    subroutine string_out_fortran (output_string) bind (C, name="fortran_string_out")
        use iso_c_binding, only: C_CHAR, c_null_char
        implicit none

        character(32) :: regular_string
        integer :: output_string_len
        character(kind=c_char, len = :), allocatable, dimension(:), intent(out) :: output_string

        integer :: i

        regular_string = "An output string"
        output_string_len = len(regular_string)

        ! create space for string to output
        allocate (character(len = 1) :: output_string(output_string_len + 1))

        ! copy arbitrary string to array of chars with null ending.
        loop_string: do i=1, output_string_len
           output_string(i) = regular_string(i:i)
        end do loop_string
        output_string(output_string_len + 1) = c_null_char

    end subroutine string_out_fortran

And here is my Java code using JNA:

public static void main(String[] args) {

        PointerByReference pp = new PointerByReference();
        FortranLibrary.INSTANCE.fortran_string_out(pp);

        final Pointer p = pp.getValue();
        // extract the null-terminated string from the Pointer
        final String val = p.getString(0);
        System.out.println("Output string:" + val);

    }

I get an empty string as val. I'm on Mac using the 16.0.3 compiler. Can anyone give me any ideas to try?

 

 

Thread Topic: 

Question

Viewing all articles
Browse latest Browse all 2583

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>