Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In my opinion it is not good practice to try to access global data in Fortran library. It can be done using COMMON blocks, but they are evil and require statically sized arrays. Generally storage association is a bad thing.</p> <p>Never access the module symbols as "__bar_MOD_a" they are compiler specific and not meant to be used directly. Pass poiters using functions and subroutines.</p> <p>Pass the array as a subroutine argument. You can also allocate the array in C and pass it to Fortran. What can be also done is getting a pointer to the first element of the array. It will serve es the C pointer to the array.</p> <p>My solution, for simplicity without the .so, it is trivial to add it:</p> <p>bar.f90</p> <pre><code>module bar use iso_C_binding implicit none integer, parameter :: pa = selected_real_kind(15, 307) real(pa), dimension(:), allocatable,target :: a integer :: as contains subroutine allocArray(asize,ptr) bind(C,name="allocArray") integer, intent(in) :: asize type(c_ptr),intent(out) :: ptr as = asize allocate(a(asize)) ptr = c_loc(a(1)) end subroutine subroutine fillArray(values) bind(C,name="fillArray") real(pa), dimension(as), intent(in) :: values a = values end subroutine subroutine printArray() bind(C,name="printArray") write(*,*) a end subroutine end module </code></pre> <p>main.c</p> <pre><code>#include &lt;dlfcn.h&gt; #include &lt;stdio.h&gt; int main() { int i, k = 4; double arr[k]; char * e; double *a; void allocArray(int*,double**); void fillArray(double*); void allocArray(); for(i = 0; i &lt; k; i++) arr[i] = i * 3.14; allocArray(&amp;k,&amp;a); fillArray(arr); printArray(); for(i = 0; i &lt; 4; i++) printf("%f ", a[i]); printf("\n"); return 0; } </code></pre> <p>compile and run:</p> <pre><code>gcc -c -g main.c gfortran -c -g -fcheck=all bar.f90 gfortran main.o bar.o ./a.out 0.0000000000000000 3.1400000000000001 6.2800000000000002 9.4199999999999999 0.000000 3.140000 6.280000 9.420000 </code></pre> <p>Note: There is no reason for the returns in your Fortran subroutines, they only obscure the code.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload