Note that there are some explanatory texts on larger screens.

plurals
  1. POWriting COM object in C# and using it from C#
    text
    copied!<p>I would like to implement a COM object in C# and also use it in C# (besides C++ and others).</p> <p>Here is the code of the DLL implementing the COM object :</p> <pre><code>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() { } } } </code></pre> <p>I've used gacutil at add the DLL to the global assembly cache.</p> <p>The EXE uses the COM object in the following way (like I successfully did with some COM objects implemented in C++):</p> <pre><code>[ 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(); } </code></pre> <p>When executing the line <em>object o = new TestObject();</em>, I get an InvalidCastException. What is wrong with this code?</p> <blockquote> <p>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.</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload