Fortran DLL and D

Michael pr at m1xa.com
Wed Mar 21 15:17:21 PDT 2012


Guys, thanks for advices.
After all I have proper code.

simple.d

import core.runtime;
import std.stdio;
import std.string;
import std.conv;

version(Windows)
{
     import core.sys.windows.windows;
     alias GetProcAddress GetProc;
}
else
     version(Linux) // not tested
     {
         import core.sys.linux.linux;
         alias dlsym GetProc;
     }

alias extern(C) void function (double *, int) func_One;
alias extern(C) void function (double *, int, ref int) func_Two;

void main(string[] args)
{
     if (args.count != 2)
         return;

     size_t size = parse!int(args[1]);

     writeln("Accept: ", size);

     double[] arr = new double[size];

     auto dllfile = "simple.dll";

     void * lib = Runtime.loadLibrary(dllfile);

     if (!lib)
     {
         writeln("Lib!");
         return;
     }

     func_One f_One = cast(func_One) GetProc(lib, 
"fOne".toStringz);
     if (f_One is null)
     {
         writeln("f_One!");
         return;
     }

     func_Two f_Two = cast(func_Two) GetProc(lib, 
"fTwo".toStringz);
     if (f_Two is null)
     {
         writeln("f_Two!");
         return;
     }

     f_One(arr.ptr, arr.length);

     writeln("array size: ", arr.length);

     for(int k = 0; k < arr.length; k++)
     {
         writeln(k + 1, '\t', arr[k]);
     }

     int ans = 0;
     f_Two(arr.ptr, arr.length, ans);

     writeln("fTwo = ", ans);

     Runtime.unloadLibrary(lib);
}

simple.f95 compiled with gfortran -shared -O3 -o simple.dll 
simple.f95

subroutine fOne(a, i) bind(C, name = "fOne")
     integer*4, value, intent(in) :: i
     real*8, dimension(i), intent(out) :: a
     print *, 'entry fortran dll'
     print *, 'size', i
     do j = 1, i
         a(j) = j * j;
         print *, j
     end do
     print *, 'exit fortran dll'
end

subroutine fTwo(a, i, ans) bind(C, name = "fTwo")
     integer*4, value, intent(in) :: i
     real*8, dimension(i), intent(in) :: a
     integer*4, intent(out) :: ans
     print *, 'entry fortran dll'
     print *, 'size', i
     if (a(1) .lt. 100) then
         print *, 'inside if'
         ans = 1
         print *, 'end if'
         return
     end if
     ans = 0
     print *, 'exit fortran dll'
end




More information about the Digitalmars-d mailing list