【问题标题】:calling unmanaged dll from C# maybe im marshalling wrong从 C# 调用非托管 dll 可能我编组错误
【发布时间】:2013-04-11 10:45:58
【问题描述】:

我不太确定我做错了什么,但我不断收到 System.ArgumentException

当我查看 IDL(由 ItyteLib Veiwer 生成)时,我可以看到结构和模块

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);

当我像这样使用 DllImport 时:

[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);

这样称呼它

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);

【问题讨论】:

标签: c# dll marshalling unmanaged


【解决方案1】:

您需要将MarshalAs 属性添加到padVpadA 数组。很可能是StructLayout 属性。

[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;
}

【讨论】:

    猜你喜欢
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 2011-02-06
    • 2011-05-22
    • 1970-01-01
    相关资源
    最近更新 更多