西門子 Prodave 是 S7 PLC 專用通訊庫,本文詳細記錄如何用 C# DllImport 封裝 Prodave6.dll,涵蓋連線管理、DB/任意區讀寫、位操作、資料型別轉換、錯誤訊息取得等完整功能,並解決共用體、指標、陣列封送等棘手互通問題。
union { uchar Mpi; uchar Ip[4]; uchar Mac[6]; } → C# 直接定義 [MarshalAs(UnmanagedType.ByValArray, SizeConst=6)] byte[] Adr,以最大成員 (6 bytes) 預留空間,實測穩定。uchar* pBuffer 視情況對應 byte[] (雙向緩衝) 或 StringBuilder (單向輸出字串)。int* → C# ref int;陣列參數不需 ref。enum,提升可讀性與型別安全。public struct CON_TABLE_TYPE
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] Adr; // MPI/IP/MAC 共用體空間
public byte AdrType; // 1=MPI, 2=IP, 3=MAC
public byte SlotNr;
public byte RackNr;
}
public enum DatType : byte { BYTE = 0x02, WORD = 0x04, DWORD = 0x06 }
public enum FieldType : byte { d = 100, D = 68, e = 101, E = 69, a = 97, A = 65, m = 109, M = 77, t = 116, T = 84 }
[DllImport("Prodave6.dll")]
public extern static int LoadConnection_ex6(int ConNr, string pAccessPoint, int ConTableLen, ref CON_TABLE_TYPE pConTable);
[DllImport("Prodave6.dll")]
public extern static int db_read_ex6(UInt16 BlkNr, DatType DType, UInt16 StartNr, ref UInt32 pAmount, UInt32 BufLen, byte[] pBuffer, ref UInt32 pDatLen);
[DllImport("Prodave6.dll")]
public extern static int field_read_ex6(FieldType FType, UInt16 BlkNr, UInt16 StartNr, UInt32 pAmount, UInt32 BufLen, byte[] pBuffer, ref UInt32 pDatLen);
[DllImport("Prodave6.dll")]
public extern static int GetErrorMessage_ex6(int ErrorNr, UInt32 BufLen, [MarshalAs(UnmanagedType.LPStr)] StringBuilder pBuffer);
// 浮點轉換、位操作、BCD 轉換、高低位交換、緩衝區複製等完整封裝見文中完整程式碼。
文末提供完整測試流程:建立連線 (IP 192.168.1.200, Slot 2, Rack 0) → 啟用連線 → DB4 寫入/讀回 20 bytes → 任意區 (DB/M) 讀寫 → M 區位讀寫 → 列舉已載入連線 → 斷線 → 取得錯誤訊息 → 浮點/位/BCD/高低位轉換驗證。
完整專案 (VS2008 SP1 Console) 與 Prodave 英文手冊 PDF 可至 CSDN 下載。注意:需安裝西門子原廠安裝程式註冊 DLL,單獨複製 DLL 無效。