2013-04-09 66 views
0

我不太知道我可能是做錯了,但我不斷收到System.ArgumentException調用從C#非託管的DLL也許我錯了編組

當我看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); 
+0

顯示您的託管'XxxStruct'。另外,你在哪一行代碼中得到了ArgumentException? – 2013-04-09 13:15:06

+0

我在這一行dat_SA(server,(short)2,xobj)得到異常; – Yeti 2013-04-10 06:55:07

+0

可能重複[System.ArgumentException從c#調用非託管dll](http://stackoverflow.com/questions/15832245/system-argumentexception-when-calling-unmanaged-dll-from-c-sharp) – 2013-04-10 13:15:01

回答

0

你需要一個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; 
}