从Fortran到C#的PInvoke

时间:2011-11-24 07:08:18

标签: pinvoke fortran

我想从Fortran编译库中导入一个函数,我可以访问的函数表单的签名是c:

typedef void (__stdcall *fp_SUBLTdllTYPE)(double &,double *,double &,long &,char*,long );

我的C#代码如下:

//(long &,char*,char*,char*,long &,char*,long ,long ,long ,long );
    [DllImport(@"C:\Program Files\REFPROP\refprop.dll",
        CallingConvention=CallingConvention.StdCall,
        CharSet = CharSet.Auto, 
        EntryPoint = "SETUPdll")
    ]
    public static extern void Setup([In] long nc,[In] 
        [MarshalAs(UnmanagedType.LPStr)] StringBuilder hfiles,
        [In] [MarshalAs(UnmanagedType.LPStr)] StringBuilder hfmix, 
        [In] [MarshalAs(UnmanagedType.LPStr)] StringBuilder hrf, 
        [In,Out] long ierr, [Out] [MarshalAs(UnmanagedType.LPStr)] StringBuilder              herr,long l1, long l2, long l3,long l4);

和fortran的定义是:

subroutine SETUP (nc,hfiles,hfmix,hrf,ierr,herr)
implicit double precision (a-h,o-z)
implicit integer (i-k,m,n)
implicit logical (l)
c
cDEC$ ATTRIBUTES DLLEXPORT :: SETUP
c     dll_export SETUP
c
parameter (ncmax=20)        !max number of components in mixture
parameter (nrefmx=10)       !max number of fluids for transport ECS
parameter (n0=-ncmax-nrefmx,nx=ncmax)
parameter (nrf0=n0)     !lower limit for transport ref fluid arrays
parameter (nrefluids=4) ! numb

问题是我无法访问Fortran编译器,而且我的fortran几乎为零。

当我从C#代码调用函数时:

long ierr=0;
long i = 2;
StringBuilder herr=new StringBuilder("");
Setup(i, new StringBuilder("R410a.mix"), new StringBuilder("hmx.bnc"), new StringBuilder("DEF"), ierr, herr, refpropcharlength * ncmax, refpropcharlength,
            lengthofreference, errormessagelength);

我收到以下错误:

  

尝试读取或写入受保护的内存。这通常是一个   表明其他内存已损坏。

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

当您需要字符串时,传递StringBuilder对象似乎不正确。作为一个起点,我会尝试传递herr.ToString()或者只是构建字符串而不是StringBuilder。