/*------------------------------------------------------ * Add OPC Item * * (ret) True OK * False NG * ------------------------------------------------------*/ public bool AddItem(string[] ItemName, int[] ClientHd, int[] ServerHd) { int iItemCount = ItemName.Length; OPCITEMDEF[] itemDef = new OPCITEMDEF[iItemCount]; OPCITEMRESULT itemResult; IntPtr ppResult; IntPtr ppErrors; IntPtr posRes; int[] errors = new int[iItemCount]; int i; for (i = 0; i < iItemCount; i++) { itemDef[i].szItemID = ItemName[i]; itemDef[i].bActive = 1; itemDef[i].hClient = ClientHd[i]; } try { switch (m_OpcdaVer) { case DEF_OPCDA.VER_30: m_OPCItem = (IOPCItemMgt)m_OPCGroup2; break; case DEF_OPCDA.VER_10: case DEF_OPCDA.VER_20: default: m_OPCItem = (IOPCItemMgt)m_OPCGroup; break; } m_OPCItem.AddItems(iItemCount, itemDef, out ppResult, out ppErrors); Marshal.Copy(ppErrors, errors, 0, iItemCount); posRes = ppResult; for (i = 0; i < iItemCount; i++) { itemResult = (OPCITEMRESULT)Marshal.PtrToStructure(posRes, typeof(OPCITEMRESULT)); if (errors[i] == 0) { ServerHd[i] = itemResult.hServer; } Marshal.DestroyStructure(posRes, typeof(OPCITEMRESULT)); // 06/09/20 for VS2005 posRes = (IntPtr)(posRes.ToInt32() + Marshal.SizeOf(typeof(OpcRcw.Da.OPCITEMRESULT))); // 06/09/20 for VS2005 //posRes = new IntPtr(posRes.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT))); } Marshal.FreeCoTaskMem(ppResult); Marshal.FreeCoTaskMem(ppErrors); } catch (Exception exc) { MessageBox.Show(exc.ToString(), "AddItem"); return(false); } // erase itemDef; // erase errors; return(true); }
public ConnectionGroup(string opcServer, string opcHost, List <OPCBaseChannel> channels) { Type t; if (opcHost.ToLowerInvariant() == "localhost") { t = Type.GetTypeFromProgID(opcServer); } else { t = Type.GetTypeFromProgID(opcServer, opcHost); } server = (IOPCServer)Activator.CreateInstance(t); int groupClientId = 1; int groupId; int updateRate = 0; object group_obj; Guid tmp_guid = typeof(IOPCItemMgt).GUID; server.AddGroup("fscdg", 1, updateRate, groupClientId, new IntPtr(), new IntPtr(), 0, out groupId, out updateRate, ref tmp_guid, out group_obj); group = (IOPCItemMgt)group_obj; IntPtr addResult = new IntPtr(); IntPtr addErrors = new IntPtr(); OPCITEMDEF[] items = new OPCITEMDEF[2]; for (int i = 0; i < channels.Count; i++) { items[0].bActive = 1; items[0].szItemID = channels[i].OpcChannel; items[0].hClient = channels[i].GetHashCode(); group.AddItems(1, items, out addResult, out addErrors); } for (int i = 0; i < channels.Count; i++) { IntPtr pos = new IntPtr(addResult.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)) * i); OPCITEMRESULT res = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT)); bool readOnly = (res.dwAccessRights & OPC_WRITEABLE) != OPC_WRITEABLE; channels[i].Connect(this, res.hServer, readOnly); } Marshal.FreeCoTaskMem(addResult); Marshal.FreeCoTaskMem(addErrors); addResult = IntPtr.Zero; addErrors = IntPtr.Zero; IConnectionPointContainer cpc = (IConnectionPointContainer)group_obj; IConnectionPoint cp; Guid dataCallbackGuid = typeof(IOPCDataCallback).GUID; cpc.FindConnectionPoint(ref dataCallbackGuid, out cp); callback = new OPCDataCallback(channels); cp.Advise(callback, out callbackCookie); }
public bool AddItems(IList <TagMetaData> items) { int count = items.Count; if (_items == null) { _items = new List <ITag>(count); mapping = new Dictionary <short, ITag>(count); } List <OPCITEMDEF> itemArray = new List <OPCITEMDEF>(count); for (int i = 0; i < count; i++) { if (items[i].GroupID == this._Id) { itemArray.Add(new OPCITEMDEF { hClient = items[i].ID, szItemID = items[i].Address, bActive = true, wReserved = (short)i }); } } IntPtr pAddResults; IntPtr pErrors; if (!HRESULTS.Succeeded(_itemMgt.AddItems(itemArray.Count, itemArray.ToArray(), out pAddResults, out pErrors))) { return(false); } int iStructSize = Marshal.SizeOf(typeof(OPCITEMRESULT)); lock (_server.SyncRoot) { for (int i = 0; i < itemArray.Count; i++) { try { if (Marshal.ReadInt32(pErrors) == 0) { ITag dataItem = null; var itemDef = itemArray[i]; //string addr = string.Concat(_serverId, ',', Marshal.ReadInt32(pAddResults)); DataType type = items[itemDef.wReserved].DataType; switch (type) { case DataType.BOOL: dataItem = new BoolTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 1, 0, DataType.BOOL), this); break; case DataType.BYTE: dataItem = new ByteTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 1, 0, DataType.BYTE), this); break; case DataType.WORD: dataItem = new UShortTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 2, 0, DataType.WORD), this); break; case DataType.SHORT: dataItem = new ShortTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 2, 0, DataType.SHORT), this); break; case DataType.INT: dataItem = new IntTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 4, 0, DataType.INT), this); break; case DataType.DWORD: dataItem = new UIntTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 4, 0, DataType.DWORD), this); break; case DataType.FLOAT: dataItem = new FloatTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 4, 0, DataType.FLOAT), this); break; case DataType.SYS: case DataType.STR: dataItem = new StringTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), 64, 0, DataType.STR), this); break; default: break; //case VarEnum.VT_ARRAY: // dataItem = new ArrayTag((short)itemDef.hClient, new DeviceAddress(-0x100, 0, 0, Marshal.ReadInt32(pAddResults), (byte)Marshal.ReadInt16(pAddResults + 18), 0, DataType.ARRAY), this); // break; } if (dataItem != null) { _items.Add(dataItem); mapping.Add((short)itemDef.hClient, dataItem); _server.AddItemIndex(items[itemDef.wReserved].Name, dataItem); } pAddResults += iStructSize; pErrors += 4; } } catch (Exception err) { if (err.Message != null) { } } } //Marshal.FreeCoTaskMem(pAddResults); //Marshal.FreeCoTaskMem(pErrors); _items.TrimExcess(); return(true); } }
public bool AddItems(OPCItemDef[] arrDef, out OPCItemResult[] arrRes) { arrRes = null; bool hasblobs = false; int count = arrDef.Length; IntPtr ptrDef = Marshal.AllocCoTaskMem(count * sizeOPCITEMDEF); int runDef = (int)ptrDef; OPCITEMDEFintern idf = new OPCITEMDEFintern(); idf.wReserved = 0; foreach (OPCItemDef d in arrDef) { idf.szAccessPath = d.AccessPath; idf.szItemID = d.ItemID; idf.bActive = d.Active; idf.hClient = d.HandleClient; idf.vtRequestedDataType = (short)d.RequestedDataType; idf.dwBlobSize = 0; idf.pBlob = IntPtr.Zero; if (d.Blob != null) { idf.dwBlobSize = d.Blob.Length; if (idf.dwBlobSize > 0) { hasblobs = true; idf.pBlob = Marshal.AllocCoTaskMem(idf.dwBlobSize); Marshal.Copy(d.Blob, 0, idf.pBlob, idf.dwBlobSize); } } Marshal.StructureToPtr(idf, (IntPtr)runDef, false); runDef += sizeOPCITEMDEF; } IntPtr ptrRes; IntPtr ptrErr; int hresult = ifItems.AddItems(count, ptrDef, out ptrRes, out ptrErr); runDef = (int)ptrDef; if (hasblobs) { for (int i = 0; i < count; i++) { IntPtr blob = (IntPtr)Marshal.ReadInt32((IntPtr)(runDef + 20)); if (blob != IntPtr.Zero) { Marshal.FreeCoTaskMem(blob); } Marshal.DestroyStructure((IntPtr)runDef, typeOPCITEMDEF); runDef += sizeOPCITEMDEF; } } else { for (int i = 0; i < count; i++) { Marshal.DestroyStructure((IntPtr)runDef, typeOPCITEMDEF); runDef += sizeOPCITEMDEF; } } Marshal.FreeCoTaskMem(ptrDef); if (HRESULTS.Failed(hresult)) { Marshal.ThrowExceptionForHR(hresult); } int runRes = (int)ptrRes; int runErr = (int)ptrErr; if ((runRes == 0) || (runErr == 0)) { Marshal.ThrowExceptionForHR(HRESULTS.E_ABORT); } arrRes = new OPCItemResult[count]; for (int i = 0; i < count; i++) { arrRes[i] = new OPCItemResult(); arrRes[i].Error = Marshal.ReadInt32((IntPtr)runErr); if (HRESULTS.Failed(arrRes[i].Error)) { continue; } arrRes[i].HandleServer = Marshal.ReadInt32((IntPtr)runRes); arrRes[i].CanonicalDataType = (VarEnum)(int)Marshal.ReadInt16((IntPtr)(runRes + 4)); arrRes[i].AccessRights = (OPCACCESSRIGHTS)Marshal.ReadInt32((IntPtr)(runRes + 8)); int ptrblob = Marshal.ReadInt32((IntPtr)(runRes + 16)); if ((ptrblob != 0)) { int blobsize = Marshal.ReadInt32((IntPtr)(runRes + 12)); if (blobsize > 0) { arrRes[i].Blob = new byte[blobsize]; Marshal.Copy((IntPtr)ptrblob, arrRes[i].Blob, 0, blobsize); } Marshal.FreeCoTaskMem((IntPtr)ptrblob); } runRes += sizeOPCITEMRESULT; runErr += 4; } Marshal.FreeCoTaskMem(ptrRes); Marshal.FreeCoTaskMem(ptrErr); return(hresult == HRESULTS.S_OK); }
/// <summary> adds an IOPCItemStateMgt-object to given group </summary> /// <param name="itemsActive"> determines which item is active </param> /// <param name="itemIDs"> determines the itemIDs </param> /// <param name="itemTypes"> the datatypes of the items </param> /// <param name="itmClntHndls"> the clientHandles of the items </param> /// <param name="itmSrvHndls"> the serverHandles given from the opc-server </param> /// <exception cref="Exception">throws and forwards any exception (with short error description)</exception> public void addOPCItems(bool[] itemsActive, // 激活 string[] itemIDs, // item id short[] itemTypes, // item的数据类型 int[] itmClntHndls, // item的client句柄数组 out int[] itmSrvHndls) // item的server句柄数组 { // initialize arguments. Guid iid = Guid.Empty; //number of elements we can add int numberOfItems = itmClntHndls.Length; OPCITEMDEF[] Itemdefs = new OPCITEMDEF[numberOfItems]; IntPtr ppResults = IntPtr.Zero; IntPtr ppErrors = IntPtr.Zero; string strDummy = ""; if (m_disposed) { throw new NullReferenceException("This object has been disposed!"); } // Init item server handles itmSrvHndls = new int[numberOfItems]; try { // Get Item interface m_OPCItem = (IOPCItemMgt)m_OPCGroupStateMgt; if (m_OPCItem == null) { strDummy = "Could not get the interface 'IOPCItemMgt'!"; throw new Exception(strDummy); } // Now add the items for (int i = 0; i < numberOfItems; i++) { // Accesspath not needed Itemdefs[i].szAccessPath = ""; // AddItem Active, so OnDataChange will come in an active group for this item Itemdefs[i].bActive = Convert.ToInt32(itemsActive[i]); // We want to get the items as string Itemdefs[i].vtRequestedDataType = itemTypes[i]; // "BinaryLargeOBject" not needed by SimaticNet OPC Server Itemdefs[i].dwBlobSize = 0; // no blob Itemdefs[i].pBlob = IntPtr.Zero; Itemdefs[i].hClient = itmClntHndls[i]; Itemdefs[i].szItemID = itemIDs[i]; } // Adding items to the Group m_OPCItem.AddItems(numberOfItems, Itemdefs, out ppResults, out ppErrors); if (ppResults == IntPtr.Zero) { strDummy = "The server did not return a result array."; throw new Exception(strDummy); } if (ppErrors == IntPtr.Zero) { strDummy = "The server did not return an arror array."; throw new Exception(strDummy); } //Evaluate return ErrorCodes to exclude possible Errors int[] errors = new int[numberOfItems]; Marshal.Copy(ppErrors, errors, 0, numberOfItems); OPCITEMRESULT[] result = new OPCITEMRESULT[numberOfItems]; IntPtr pos = ppResults; for (int dwCount = 0; dwCount < numberOfItems; dwCount++) { try { if (errors[dwCount] != 0) { strDummy = "At least one item is not added."; throw new Exception(strDummy); // 抛出异常 } // Item was added succesfully result[dwCount] = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT)); itmSrvHndls[dwCount] = result[dwCount].hServer; } catch (Exception) { // Item was not added throw; } pos = (IntPtr)(pos.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT))); } m_itmServerHandles = new int[numberOfItems]; m_itmServerHandles = itmSrvHndls; // Free allocated COM-ressouces Marshal.FreeCoTaskMem(ppResults); Marshal.FreeCoTaskMem(ppErrors); } catch (Exception) { // Free allocated COM-ressouces Marshal.FreeCoTaskMem(ppResults); Marshal.FreeCoTaskMem(ppErrors); throw; } }
/// <summary> /// Adds all items to the group that have not already been added. /// </summary> public void AddItems() { // count the number of items to add. List <GroupItem> itemsToAdd = new List <GroupItem>(); lock (Lock) { for (int ii = 0; ii < m_items.Count; ii++) { if (!m_items[ii].Created) { itemsToAdd.Add(m_items[ii]); } } } // check if nothing to do. if (itemsToAdd.Count == 0) { return; } // create item definitions. int count = itemsToAdd.Count; OpcRcw.Da.OPCITEMDEF[] definitions = new OpcRcw.Da.OPCITEMDEF[count]; for (int ii = 0; ii < count; ii++) { definitions[ii] = new OpcRcw.Da.OPCITEMDEF(); definitions[ii].szItemID = itemsToAdd[ii].ItemId; definitions[ii].bActive = (itemsToAdd[ii].Active) ? 1 : 0; definitions[ii].szAccessPath = String.Empty; definitions[ii].vtRequestedDataType = (short)VarEnum.VT_EMPTY; definitions[ii].hClient = itemsToAdd[ii].ClientHandle; } // initialize output parameters. IntPtr pResults = IntPtr.Zero; IntPtr pErrors = IntPtr.Zero; // add items to group. string methodName = "IOPCItemMgt.AddItems"; try { IOPCItemMgt server = BeginComCall <IOPCItemMgt>(methodName, true); server.AddItems( count, definitions, out pResults, out pErrors); } catch (Exception e) { ComUtils.TraceComError(e, methodName); for (int ii = 0; ii < itemsToAdd.Count; ii++) { itemsToAdd[ii].ErrorId = Marshal.GetHRForException(e); } return; } finally { EndComCall(methodName); } // unmarshal output parameters. int[] serverHandles = GetItemResults(ref pResults, count, true); int[] errors = ComUtils.GetInt32s(ref pErrors, count, true); // save handles and error codes. for (int ii = 0; ii < count; ii++) { GroupItem item = itemsToAdd[ii]; item.ServerHandle = serverHandles[ii]; item.ErrorId = errors[ii]; if (item.ErrorId >= 0) { itemsToAdd[ii].Created = true; } } /* * Utils.Trace( * "Group {0} AddItems({4}/{5}) {1}/{2}ms {3}%", * m_clientHandle, * m_samplingInterval, * m_actualSamplingInterval, * m_deadband, * itemsToAdd.Count, * m_items.Count); */ }
static void Main(string[] args) { Server server = new Server(); int TimeBias = 0; float DeadBand = 0.0f; uint phServerGroup; uint UpdateRate; var id = typeof(IOPCItemMgt).GUID; object p; server.AddGroup("Group1", 1, 10, 1, ref TimeBias, ref DeadBand, 0, out phServerGroup, out UpdateRate, ref id, out p); IOPCItemMgt pOPCItemMgt = (IOPCItemMgt)p; Item[] items = new Item[3]; items[0].Active = false; items[0].AccessPath = null; items[0].ClientId=1; items[0].ItemId="ItemY1"; items[0].RequestedDataSubType = VarEnum.VT_R8; items[0].RequestedDataType=VarEnum.VT_EMPTY; items[1].Active = false; items[1].AccessPath = null; items[1].ClientId = 2; items[1].ItemId = "ItemY2"; items[1].RequestedDataSubType = VarEnum.VT_R8; items[1].RequestedDataType = VarEnum.VT_EMPTY; items[2].Active = false; items[2].AccessPath = null; items[2].ClientId = 3; items[2].ItemId = "ItemY3"; items[2].RequestedDataSubType = VarEnum.VT_R8; items[2].RequestedDataType = VarEnum.VT_EMPTY; IntPtr itemPtr = OPCHelper.GetIntPtrfromItemArray(items); IntPtr dataPtr; IntPtr errorsPtr; pOPCItemMgt.AddItems(3, itemPtr, out dataPtr, out errorsPtr); IOPCSyncIO syncIO = (IOPCSyncIO)p; int[] serverIds = { 0, 1, 2 }; IntPtr dataPtr1; IntPtr errorsPtr1; Console.WriteLine("Y1 Y2 Y3"); for (int i = 0; i < 100; ++i) { syncIO.Read(DataSource.Cache, 3, serverIds, out dataPtr1, out errorsPtr1); ItemValue[] temItem = OPCHelper.GetSignalsState(3, dataPtr1, errorsPtr1); for (int k = 0; k < 3; ++k) { if (temItem[k].Error < 0) { Console.WriteLine("Error!"); return; } } double signal_Y1=(double)temItem[0].Value; double signal_Y2=(double)temItem[1].Value; double signal_Y3=(double)temItem[2].Value; Console.WriteLine("{0} {1} {2}", signal_Y1, signal_Y2, signal_Y3); System.Threading.Thread.Sleep(100); } }
private void RegItemsInServer() { int dwCount = Items.Count(); Type type = typeof(tagOPCITEMDEF); IntPtr pItems = Marshal.AllocCoTaskMem((int)dwCount * Marshal.SizeOf(type)); m_dwReadCount = 0; indecies.Clear(); tagOPCITEMDEF[] itemDefs = new tagOPCITEMDEF[dwCount]; for (int i = 0; i < dwCount; i++) { OPCItem item = ((List <OPCItem>)Items)[i]; if (item.Enabled) { itemDefs[m_dwReadCount] = item.GetItemDef(); Marshal.StructureToPtr(itemDefs[m_dwReadCount], pItems + m_dwReadCount * Marshal.SizeOf(type), false); indecies.Add((uint)m_dwReadCount); m_dwReadCount++; } } IntPtr iptrErrors = IntPtr.Zero; IntPtr iptrResults = IntPtr.Zero; try { // Добавляем элемент данных в группу m_pItemMgt.AddItems((uint)m_dwReadCount, pItems, out iptrResults, out iptrErrors); } catch (ApplicationException ex) { Console.Out.WriteLine(ex.Message); } m_hItems = new uint[m_dwReadCount]; tagOPCITEMRESULT[] pResults = new tagOPCITEMRESULT[m_dwReadCount]; m_hRes = new int[dwCount]; Marshal.Copy(iptrErrors, m_hRes, 0, dwCount); try { for (int i = 0; i < m_dwReadCount; i++) { pResults[i] = (tagOPCITEMRESULT)Marshal.PtrToStructure(iptrResults + i * Marshal.SizeOf(typeof(tagOPCITEMRESULT)), typeof(tagOPCITEMRESULT)); m_hItems[i] = pResults[i].hServer; //Генерируем исключение в случае ошибки в HRESULT Marshal.ThrowExceptionForHR(m_hRes[i]); } } catch (System.Exception ex) { Console.Out.WriteLine(ex.Message); string msg; //Получаем HRESULT соответствующий сгененрированному исключению int hRes = Marshal.GetHRForException(ex); throw new ServerException(hRes); } Marshal.FreeCoTaskMem(pItems); Marshal.FreeCoTaskMem(iptrErrors); Marshal.FreeCoTaskMem(iptrResults); }
public bool AddItems(OPCItemDef[] p_ArrDef, out OPCItemResult[] p_ArrRes) { p_ArrRes = null; bool l_HasBlobs = false; int l_Count = p_ArrDef.Length; IntPtr l_PtrDef = Marshal.AllocCoTaskMem(l_Count * m_SizeOPCItemDef); int l_RunDef = (int)l_PtrDef; OPCItemDefIntern l_ItmDefIntrn = new OPCItemDefIntern(); l_ItmDefIntrn.Reserved = 0; for (int i = 0; i < p_ArrDef.Length; ++i) { OPCItemDef l_ItmDef = p_ArrDef[i]; l_ItmDefIntrn.AccessPath = l_ItmDef.AccessPath; l_ItmDefIntrn.ItemID = l_ItmDef.ItemID; l_ItmDefIntrn.Active = l_ItmDef.Active; l_ItmDefIntrn.Client = l_ItmDef.HandleClient; l_ItmDefIntrn.RequestedDataType = (short)l_ItmDef.RequestedDataType; l_ItmDefIntrn.BlobSize = 0; l_ItmDefIntrn.Blob = IntPtr.Zero; if (l_ItmDef.Blob != null) { l_ItmDefIntrn.BlobSize = l_ItmDef.Blob.Length; if (l_ItmDefIntrn.BlobSize > 0) { l_HasBlobs = true; l_ItmDefIntrn.Blob = Marshal.AllocCoTaskMem(l_ItmDefIntrn.BlobSize); Marshal.Copy(l_ItmDef.Blob, 0, l_ItmDefIntrn.Blob, l_ItmDefIntrn.BlobSize); } } Marshal.StructureToPtr(l_ItmDefIntrn, (IntPtr)l_RunDef, false); l_RunDef += m_SizeOPCItemDef; } IntPtr l_PtrRes; IntPtr l_PtrErr; int l_HResult = m_IfItems.AddItems(l_Count, l_PtrDef, out l_PtrRes, out l_PtrErr); l_RunDef = (int)l_PtrDef; if (l_HasBlobs) { for (int i = 0; i < l_Count; ++i) { IntPtr l_Blob = (IntPtr)Marshal.ReadInt32((IntPtr)(l_RunDef + 20)); if (l_Blob != IntPtr.Zero) { Marshal.FreeCoTaskMem(l_Blob); } Marshal.DestroyStructure((IntPtr)l_RunDef, m_TypeOPCItemDef); l_RunDef += m_SizeOPCItemDef; } } else { for (int i = 0; i < l_Count; ++i) { Marshal.DestroyStructure((IntPtr)l_RunDef, m_TypeOPCItemDef); l_RunDef += m_SizeOPCItemDef; } } Marshal.FreeCoTaskMem(l_PtrDef); if (HResults.Failed(l_HResult)) { Marshal.ThrowExceptionForHR(l_HResult); } int l_RunRes = (int)l_PtrRes; int l_RunErr = (int)l_PtrErr; if ((l_RunRes == 0) || (l_RunErr == 0)) { Marshal.ThrowExceptionForHR(HResults.E_ABORT); } p_ArrRes = new OPCItemResult[l_Count]; for (int i = 0; i < l_Count; ++i) { p_ArrRes[i] = new OPCItemResult(); p_ArrRes[i].Error = Marshal.ReadInt32((IntPtr)l_RunErr); if (HResults.Failed(p_ArrRes[i].Error)) { continue; } p_ArrRes[i].HandleServer = Marshal.ReadInt32((IntPtr)l_RunRes); p_ArrRes[i].CanonicalDataType = (VarEnum)(int)Marshal.ReadInt16((IntPtr)(l_RunRes + 4)); p_ArrRes[i].AccessRights = (OPCAccessRights)Marshal.ReadInt32((IntPtr)(l_RunRes + 8)); int l_PtrBlob = Marshal.ReadInt32((IntPtr)(l_RunRes + 16)); if (l_PtrBlob != 0) { int l_BlobSize = Marshal.ReadInt32((IntPtr)(l_RunRes + 12)); if (l_BlobSize > 0) { p_ArrRes[i].Blob = new byte[l_BlobSize]; Marshal.Copy((IntPtr)l_PtrBlob, p_ArrRes[i].Blob, 0, l_BlobSize); } Marshal.FreeCoTaskMem((IntPtr)l_PtrBlob); } l_RunRes += m_SizeOPCItemResult; l_RunErr += 4; } Marshal.FreeCoTaskMem(l_PtrRes); Marshal.FreeCoTaskMem(l_PtrErr); return(l_HResult == HResults.S_OK); }
public void AddItems(string[] itemID, out int[] ItemHANDLES, out VarEnum[] arrayType) { int m_Res = 0; try { int dwCount = itemID.Length; IntPtr pErrors; IntPtr pResults; IOPCItemMgt m_pIItemMgt = (IOPCItemMgt)pUnknown; //ItemMgt: OK OPCITEMDEF pItem = new OPCITEMDEF(); //set pItem int temp = 0; pItem.bActive = true; pItem.szAccessPath = null; pItem.hClient = temp; pItem.dwBlobSize = 0; // no blob support pItem.pBlob = IntPtr.Zero; pItem.vtRequestedDataType = (int)VarEnum.VT_EMPTY; pItem.wReserved = 0; //alloc memory IntPtr ptrDef = Marshal.AllocCoTaskMem(dwCount * Marshal.SizeOf(pItem)); int runDef = (int)ptrDef; for (int i = 0; i < dwCount; i++) { pItem.szItemID = itemID[i]; Marshal.StructureToPtr(pItem, (IntPtr)runDef, false); runDef += Marshal.SizeOf(pItem); } //add item m_Res = m_pIItemMgt.AddItems(dwCount, ptrDef, out pResults, out pErrors); //dealoc memory runDef = (int)ptrDef; for (int i = 0; i < dwCount; i++) { Marshal.DestroyStructure((IntPtr)runDef, pItem.GetType()); runDef += Marshal.SizeOf(pItem); } Marshal.FreeCoTaskMem(ptrDef); if (m_Res < 0) { throw new Exception("Server: Add Items failed hr= " + m_Res.ToString()); } //read result int runRes = (int)pResults; int runErr = (int)pErrors; if ((runRes == 0) || (runErr == 0)) { throw new Exception("Server: Add Items failed hr= " + unchecked ((int)0x80004004).ToString()); } //init output arry ItemHANDLES = new int[dwCount]; arrayType = new VarEnum [dwCount]; int error; for (int i = 0; i < dwCount; i++) { error = Marshal.ReadInt32((IntPtr)runErr); if (error < 0) { //parent.PrintMessage("Server: Add Item " + itemID[i] + " is failed hr =" + error.ToString(), MessageStyl.error); ItemHANDLES[i] = 0; arrayType[i] = VarEnum.VT_EMPTY; } else { ItemHANDLES[i] = Marshal.ReadInt32((IntPtr)runRes); arrayType[i] = (VarEnum)(int)Marshal.ReadInt16((IntPtr)(runRes + 4)); //set server handle same as client handle int[] tempHandle = new int[1]; tempHandle[0] = ItemHANDLES[i]; IntPtr setClientError; m_pIItemMgt.SetClientHandles(1, tempHandle, tempHandle, out setClientError); int s_err = Marshal.ReadInt32(setClientError); //if (s_err < 0) parent.PrintMessage("Server: Add Item " + itemID[i] + " : Set the client handle is failed hr =" + s_err.ToString(), MessageStyl.error); } runRes += Marshal.SizeOf(new OPCITEMRESULT()); runErr += 4; } Marshal.FreeCoTaskMem(pResults); Marshal.FreeCoTaskMem(pErrors); } catch (Exception e) { //parent.PrintMessage(e.Message, MessageStyl.error); throw e; } }