简体   繁体   中英

calling unmanaged dll from C# maybe im marshalling wrong

I'm not quite sure what i might be doing wrong but i keep getting System.ArgumentException

when i look at the IDL(generated by ITyteLib Veiwer) I can see both struct and modules

typedef struct tagXxxStruct {        
 short type;
 short file;   
 short rec;
 short word;
 short start_bit;        
 short length;        
 short flags;
 short padding;
 short value;
 short padV[3];
 short status;
 short padA[3];
} XxxStruct;

[entry("dat"), helpstring("...")]
short _stdcall dat_Int(
                [in] LPSTR Server, 
                [in] short num_points, 
                [in, out] SAFEARRAY(XxxStruct)* XxxStruct_data);

I when use DllImport like so:

[DllImport("hscnetapi.dll", EntryPoint = "dat", CallingConvention = CallingConvention.StdCall)]
public static extern unsafe short dat_SA([MarshalAs(UnmanagedType.LPStr)] string host, short num_points, [MarshalAs(UnmanagedType.SafeArray)] XxxStruct[] dat_data);

And call it like so

public struct XxxStruct
    {
        public short type;
        public short file;
        public short rec;
        public short word;
        public short start_bit;
        public short Length;
        public short Flags;
        public short padding;
        public short value;
        public short[] padV;
        public short Status;
        public short[] padA;
    }

server = "localhost";

XxxStruct[] xobj= new XxxStruct[2];

 for (i = 0; i <= 1; i++)
        {

            var _with1 = xobj[i];
            _with1.type = 2;
            _with1.file = 8;
            _with1.rec = 1;
            _with1.word = ((short)(359 + (i)));
            _with1.Flags = 0;
            _with1.padV = new short[3];
            _with1.padA = new short[3];
            xobj[i] = _with1;
        }

dat_SA(server, (short)2, xobj);

You need to add a MarshalAs attribute to the padV and padA arrays. And quite possibly a StructLayout attribute.

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct XxxStruct
{
    public short type;
    public short file;
    public short rec;
    public short word;
    public short start_bit;
    public short Length;
    public short Flags;
    public short padding;
    public short value;
    [MarshalAs(UnmanagedType.LPArray, SizeConst=3)]
    public short[] padV;
    public short Status;
    [MarshalAs(UnmanagedType.LPArray, SizeConst=3)]
    public short[] padA;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM