We help IT Professionals succeed at work.

accessviolationexception when a I call a FORTRAN dll file from visual basic 2008

In doing a project with several FORTRAN routines.

I call this routines using a DLL

this how a declare the routine
Declare Sub ENV Lib "PCTSAG.dll" (ByVal TcPcWZ As Double, ByVal K1 As Double, ByVal K2 As Double, ByVal TbPbTrPr As Double, ByVal Cf As Double, ByVal M As Double, ByVal Param As Double, ByVal opt As Long, ByVal nvec As Long, ByVal n As Short, ByVal ib As Short, ByVal ir As Short, ByVal iecuacion As Short)

Open in new window

and this is how I call the routine  
Sub example()
    dim TcPcWZ(0, 0) As Double
    dim K1(0, 0) As Double
    dim K2(0, 0) As Double
    dim TbPbTrPr(199, 3) As Double
    dim mat_example(200, 3) As Double
        Dim n As Integer
        Dim ib As Integer
        Dim ir As Integer
        Dim opt As Long
        Dim Cf(0) As Double
        Dim M(0) As Double
        Dim Param(2) As Double

        n = caracterizacion.matriz_carac.RowCount - 1
        opt = 0

        ReDim TcPcWZ(n, 3)
        ReDim K1(n, n)
        ReDim K2(n, n)
        Cf(0) = 0.1
        M(0) = 0.1
        For i = 0 To 2
            Param(i) = 0.1
        Next i

        For i = 0 To n
            TcPcWZ(i, 0) = caracterizacion.matriz_carac(4, i).Value
            TcPcWZ(i, 1) = caracterizacion.matriz_carac(5, i).Value
            TcPcWZ(i, 2) = caracterizacion.matriz_carac(6, i).Value
            TcPcWZ(i, 3) = caracterizacion.matriz_carac(0, i).Value
            For j = 0 To n
                K1(i, j) = kij(j, i)
                K2(i, j) = kbij(j, i)


        Call ENV(TcPcWZ(0, 0), K1(0, 0), K2(0, 0), TbPbTrPr(0, 0), Cf(0), M(0), Param(0), opt, 1, n, ib, ir, ParCar.ieq)
msgbox(TbPbTrPr(0, 0))
    End Sub

Open in new window

when  I try to use the routine ENV VB always show the following error: accessviolationexception attempted to read or write protected memory
    Checking in google I found that if change the declaration of the routine from ByVal to ByRef it works

   I Would like to know why it works when I do that change on the declaration.?????
Watch Question

Most Valuable Expert 2012
Top Expert 2014

It should have been the opposite. I dont know why but the difference between byval and byref is that a copy of the variable is passed in byval and a reference to original variable is passed in byref.
Fortran assumes that arguments are always passed to subroutines by reference, i.e. as a pointer to the actual value, so it is normal that, when interfacing a plain Fortran routine from another language, the parameters have to be declared being "by reference" in the interface definition.

Things can be changed on Fortran side (i.e. forcing arguments to be "by value") by using, when available, some compiler-specific non-portable options or by using the new Fortran 2003 C-Fortran bindings, which are a part of standard Fortran.