Question

Visual Studio 2008 (C#) created the Interop for my COM objects. The main objects which I am using are: OPCHDAServerClass, IOPCHDAItems, and OPCHDAItem. The code is:

OPCHDAServerClass server = new OPCHDAServerClass();
server.Connect("OPC.PHDServerHDA.1");
OPCHDAItem item = server.OPCHDAItems.AddItem("MyItem",1);

In the third line the AddItem method should return an OPCHDAItem. The interop definition for AddItem is:

[DispId(1610743813)]
OPCHDAItem AddItem(string ItemID, int ClientHandle);

The exception that I get is:

Unable to cast object of type 'OPCHDAServerClass' to type 'IOPCHDAItems'.

I do not understand why I am getting this error message. server.OPCHDAItems implements IOPCHDAItems. I do not know why server (OPCHDAServerClass) is being cast to IOPCHDAItems?

I did initial prototyping in python which worked fine so I know that the COM components are functional. This is the python code:

server = win32com.client.dynamic.Dispatch("Uniformance.OPCHDA.Automation.1")
server.Connect("OPC.PHDServerHDA.1")
item = server.OPCHDAItems.AddItem("MyItem", 1)

Has anyone seen a similar issue and know of a work around?

Pas de solution correcte

Autres conseils

Looks like the declared type of property OPCHDAItems is not IOPCHDAItems - it's OPCHDAServerClass. C# is a statically typed language - it won't typecast COM interfaces unless explicitly told to, and it won't go for the IDispatch unless told to. Rephrase like this:

server.Connect("MyServerName");
OPCHDAItem item = (server.OPCHDAItems as IOPCHDAItems).AddItem("MyItem",1);

EDIT: try this first:

IOPCHDAItems Items = server.OPCHDAItems;

Still the same error? How about

IOPCHDAItems Items = server.OPCHDAItems as IOPCHDAItems;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top