I would like to implement a COM object in C # and also use it in C # (except for C ++ and others).
Here is the DLL code that implements the COM object:
namespace TestComServer { [ComVisible(true), Guid("565D8202-6C0F-4AAB-B0F6-49719CD13045"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown) ] public interface ITestObject { void DoSomething(); } [ ComVisible(true), GuidAttribute("21293767-A713-49E2-968E-7DDE0B0DAB94"), ClassInterface(ClassInterfaceType.None) ] public class TestObject : ITestObject { public TestObject() { } public void DoSomething() { } } }
I used gacutil to add a DLL to the global assembly cache.
EXE uses a COM object as follows (for example, I have successfully dealt with some COM objects implemented in C ++):
[ ComImport(), Guid("565D8202-6C0F-4AAB-B0F6-49719CD13045"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown) ] public interface ITestObject { [PreserveSig ] void DoSomething(); } [ComImport, Guid("21293767-A713-49E2-968E-7DDE0B0DAB94")] public class TestObject { } private void button1_Click(object sender, EventArgs e) { object o = new TestObject(); ITestObject t = (ITestObject)o; t.DoSomething(); }
When executing the line object o = new TestObject () ;, I get an InvalidCastException. What is wrong with this code?
An unhandled exception of type "System.InvalidCastException" occurred in Test.exe. Additional information: Das Objekt des Typs "TestComServer.TestObject" kann nicht in Typ "TestObject" umgewandelt werden.
source share