BIND(C) Results in a Seg Fault Returning Int Values

BIND(C) Results in a Seg Fault Returning Int Values

TWare's picture

I'm slightly confused about the use of BIND(C) for calling C functions that return a value.

As background, I have a library of C functions that I'm calling via a module-interface using only !DEC$ declarations. A typical declaration would be for calling the C function is:

!DEC$ATTRIBUTES C, DLLIMPORT, ALIAS:'_xlCreateBookA':: xlCreateBook

This worked fine with the Mac Fortran compiler, but the Linux compiler complained about DLLIMPORT. So, to correct the compiler issue, and to be more modern, I tried rewriting the interfaces to use BIND(C). Some work, some don't.

An example of a successful conversion that eliminates the use of !DEC$ follows:

Integer (LPTRZ) Function xlCreateBook()
!^ A pointer is returned.
!DEC$ATTRIBUTES C, DLLIMPORT, ALIAS:'_xlCreateBookA':: xlCreateBook
import
End Function

was changed to:

Integer (C_INTPTR_T) Function xlCreateBook() &
& Bind(C,Name='xlCreateBookA')
Use, Intrinsic :: ISO_C_Binding
!^ A pointer is returned.
End Function xlCreateBook

An example of a conversion that doesn't work follows:

Integer (LSINTZ) Function xlBookLoad(pBook,filename)
!^P Loads a file into memory.
!DEC$ATTRIBUTES C, DLLIMPORT, ALIAS:'_xlBookLoadA':: xlBookLoad
!DEC$ATTRIBUTES REFERENCE :: filename
import
Integer (LPTRZ) :: pBook
Character (Len=*) :: filename
End Function

was changed to:

Integer (C_INT) Function xlBookLoad(pBook,cFname) &
& Bind(C,Name='xlBookLoadA')
Use, Intrinsic :: ISO_C_Binding
!^P Loads a spreadsheet file into memory.
Integer (C_INTPTR_T) :: pBook
Character (C_CHAR), Dimension (*) :: cFname
End Function xlBookLoad

The above routine compiles with both the Mac and Linux compilers, but both result in a seg fault at execution.

If I remove BIND(C) and use !DEC$ instead, for example:

Integer (C_INT) Function xlBookLoad(pBook,cFname)
!DEC$ATTRIBUTES C, DECORATE, ALIAS:'xlBookLoadA' :: xlBookLoad
Use, Intrinsic :: ISO_C_Binding
!^P Loads a spreadsheet file into memory.
Integer (C_INTPTR_T) :: pBook
Character (C_CHAR), Dimension (*) :: cFname
End Function xlBookLoad

it works!

Why is it that BIND(C) returns a pointer value (the first example), and not an int value (the preceding example)?

Or, what am I doing wrong?

Oh, the C library is a commercial product, LIBXL, so I can't really provide working examples. But, I will try to answer any follow-on questions about the library and C interfaces.

Thanks in advance for any help!

Dean B Jones TransWare Enterprises Inc.
3 posts / 0 new
Last post
For more complete information about compiler optimizations, see our Optimization Notice.
KEERIYAT  P.'s picture

Where is my original post?

Chief Executive Officer
TWare's picture

No idea

Dean B Jones TransWare Enterprises Inc.

Login to leave a comment.