Fwd: Problem calling C .dll library from Fortran using ISO_C_BINDING

Pietro Ghillani ghillo.p@gmail.com
Tue May 21 16:42:00 GMT 2013


Hi everyone!
I am writing Fortran code on Windows 7 32-bit with MinGW.
I am using the Fortran 2003 feature that allows to access APIs
contained in a third party .dll library (probably) written in C with
some success as I have been able to call an initialization function
and a function that returns the library version.

The problems come when I try to call a function to create a new file
that requires three arguments: a file ID, the path to the file
including its name and the path to a folder to store the temporary
files. The documentation defines the syntax of the function as
follows:

long NewFile(long fID, char* Filename, char* Path)

In Fortran I have created an interface:

INTERFACE
FUNCTION NewFile(uID,FileName,Path) BIND(C, NAME='NewFile')
USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_CHAR, C_LONG
   IMPLICIT NONE
   INTEGER(C_LONG) :: NewFile
   INTEGER(C_LONG), VALUE :: fID
   CHARACTER(C_CHAR) :: Filename(*)
   CHARACTER(C_CHAR) :: Path(*)
END FUNCTION
END INTERFACE

Then I call the function with:

iErr = NewFile(10,C_CHAR_'C:\\Windows\\Temp\\File.ext'// C_NULL_CHAR, &
C_CHAR_'C:\\Windows\\Temp'// C_NULL_CHAR)

The compilation of the test program Demo.exe is made very simply with:
gfortran -c APICall.f90 (containing the interfaces)
gfortran -c APIConst.f90 (containing the definition of some constant values)
gfortran -c APIDemo.f90 (containing the main demo program)

and then I link everything with:
gfortran -o APIDemo.exe APIDemo.o APIConst.o APICall.o API.a

where the import library API.a was created from the .dll and a .def file with:
dlltool -d API.def -l API.a

Unfortunately, at runtime the program crashes with the message:
Program received signal SIGSEGV: Segmentation fault - invalid memory reference.
Backtrace for this error:
#0 6f6a5456
#1 6f69321f
#2 004011e9

I suspect that the problem regards the definition of the char
arguments. Unfortunately, I am not very familiar with C language and,
to be honest, I don't know the meaning of those "char*" in the syntax
(I know that "char *Filename" would be a pointer, but "char* Filename"
is beyond my knowledge).

Thank in advance for any help on solving this!

Pietro



More information about the Gcc-help mailing list