Search code examples
c#.netopc-da

SafeArrayTypeMismatchException: The specified array is not of the expected type


I'm trying to read data from OPC DA Server. I'm using the method SyncRead SyncRead(short Source, int NumItems, ref Array ServerHandles, out Array Values, out Array Errors, out object Qualities, out object TimeStamps); The problem is that I don't know exactly the type of the Array of parameter Values. I'm doing it like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OPCAutomation;
using EasyModbus;
using System.Threading;
using System.IO;


Array ServerHandles = new Array[ObjOPCGroup.OPCItems.Count];
Array Values = new Array[ObjOPCGroup.OPCItems.Count];
Array Errors = new Array[ObjOPCGroup.OPCItems.Count];
object Qualities = new object();
object TimeStamps = new object();
Array Values = new Array[ObjOPCGroup.OPCItems.Count];

ObjOPCGroup.SyncRead(
   (short)OPCDataSource.OPCDevice,
   ObjOPCGroup.OPCItems.Count,
   ref ServerHandles,
   out Values,
   out Errors,
   out Qualities,
   out TimeStamps
   );

when I start the application, I get the error: System.Runtime.InteropServices.SafeArrayTypeMismatchException: The specified array is not of the expected type

Anybody can help me?

Thanks


Solution

  • new Array[length] is an array of arrays; you probably wanted an array of something more appropriate, for example a new int[length] for an array of integers, or new string[length] for an array of strings. We don't know what the API is here, so we can't tell you what they should be. But they almost certainly shouldn't be arrays of Array.

    Additionally: most of these are passed as out parameters, so you probably don't even need to initialize anything except ServerHandles. The rest could presumably all be null? or just initialized via out var i.e.

    Array serverHandles = new SomeOtherTypeHere[ObjOPCGroup.OPCItems.Count];
    
    ObjOPCGroup.SyncRead(
       (short)OPCDataSource.OPCDevice,
       ObjOPCGroup.OPCItems.Count,
       ref serverHandles,
       out var values,
       out var errors,
       out var qualities,
       out var timeStamps
       );