开发者

MarshalAs question in C#

开发者 https://www.devze.com 2023-03-18 17:30 出处:网络
I\'m having trouble receiving data from an external dll routine. The dll is to read data from a mirco-controller chip.This works fine in Delphi,and I\'m trying to get it to work in C#.

I'm having trouble receiving data from an external dll routine. The dll is to read data from a mirco-controller chip. This works fine in Delphi,and I'm trying to get it to work in C#.

Adr: Starting address Len: Total length of the data being read

The function returns a TData array where the item with index 0 contains the starting address and the item with index 1 contains the length of the data received. Following items (index 2 and higher) contain the data received. If the Receive operation fails, the length value returned in the array is set to zero

  [DllImport("dsio.dll", CallingConvention = CallingConvention.StdCall)]
  [return: MarshalAs(UnmanagedType.LPArray)]
  public static extern byte[] Receive(int Adr, int Len);

  private void BtnReceive_Click(object sender, EventArgs e)
     {
        开发者_如何学Go byte[] Data = new byte[256];
         int Adr = 0x05;
         int Len = 8;

         Data = Receive(Adr, Len);
         txtBox2.Text = Data;
     }


Firstly, it is unnecessary to instantiate new byte[256] since you are setting Data to the return result of Receive().

You should try removing the [return: MarshalAs] attribute to see if the default marshalling work.

If it does not work, this documentation indicates that SizeConst and SizeParamIndex should also be set in the MarshalAs attribute declaration when using UnmanagedType.LPArray. I do not know whether you need to use one or both of those parameters (read the linked documentation and experiment). SizeParamIndex, if needed, will be 1 because the second argument is the length.

[return: MarshalAs( UnmanagedType.LPArray, SizeConst = 256, SizeParamIndex = 1 )]

Addendum: Since you declare TData as a type, that gives me an idea that using a struct in C# may also work, and it helps isolate the first 2 bytes if it does:

[StructLayout( LayoutKind.Sequential )]
public struct TData {
    public byte StartAddress = 0;
    public byte Length = 0;
    public byte[] Data = new byte[ 254 ];
}

If you try to use this, I'm pretty sure you remove return: MarshalAs and default marshaling should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号