How do I use C# to call a function that receives a Delphi open-array parameter?

后端 未结 2 1520
小鲜肉
小鲜肉 2021-01-13 03:00

How do I convert the Delphi code into C#? It takes an array of Byte, but I\'m not sure what the C# equivalent is. My attempt doesn\'t work and throws exceptions

2条回答
  •  耶瑟儿~
    2021-01-13 03:49

    This is the way how I implemented successfully sending arrays from and to Delphi & C#.

    C#:

    [DllImport("Vendors/DelphiCommunication.dll", CallingConvention = CallingConvention.StdCall)]
    public static extern void LoadFromFileCHR(
        string sFileName,
        ref int iSize,
        ref double AreaCoef,
        ref double FWaveLength,
        ref bool FHasWaveLength,
        double[] ChromX,
        double[] ChromY
    );
    

    Note that single types have REF and arrays DO NOT HAVE REF, but arrays will still work like REF anyway

    Delphi:

    Type    
        ArrayDouble100k = array [0..99999] of Double;
    
    procedure LoadFromFileCHR(
        FileName : String;
        var Size : Integer;
        var AreaCoef : Double;
        var FWaveLength: Double;
        var FHasWaveLength : Boolean;
        var ChromX : ArrayDouble100k;
        var ChromY : ArrayDouble100k); StdCall;
    begin
       //...
    end;
    
    exports LoadFromFileCHR;
    

    Note that VAR is also with Array parameters (Delphi analog of REF).

    I had all sorts of errors, because I had ref with arrays in C# code

    Another problem that caused memory corruption for me was that I did not notice that these codes are not the same in Delphi and C#:

    Delphi:

    for i := 0 to Length(fileCHR.ChromX) do //This is wrong
    

    C#

    for(int i = 0; i < fileCHR.ChromX.Length; i++)
    

    The same in delphi would be

    for i := 0 to Length(fileCHR.ChromX) - 1 do //This is right
    

    If you overflow boundaries of arrays passed to delphi it could also cause all sorts of errors

提交回复
热议问题