Writing a COM object in C # and using it with C #

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.

+4
source share
1 answer

If you change the EXE so that it imports the interface, then instantiate the object using Type.GetTypeFromCLSID and Activator.CreateInstance:

 [ ComImport(), Guid("565D8202-6C0F-4AAB-B0F6-49719CD13045"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown) ] public interface ITestObject { [PreserveSig ] void DoSomething(); } private void button1_Click(object sender, EventArgs e) { Type type = Type.GetTypeFromCLSID(new Guid("21293767-A713-49E2-968E-7DDE0B0DAB94")); object o = Activator.CreateInstance(type); ITestObject t = (ITestObject)o; t.DoSomething(); } 

I have not used this method to import COM objects before, so this may not work. As a rule, I define my interfaces in a separate assembly, which is also available for COM, which is referenced by both DLL and EXE. The EXE creates an instance of the DLL using the above method and passes it to the .NET interface that it referenced.

0
source

Source: https://habr.com/ru/post/1399895/


All Articles