I would like to implement a COM object in C# and also use it in C# (besides C++ and others).
Here is the code of the DLL implementing 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've used gacutil at add the DLL to the global assembly cache.
The EXE uses the COM object in the following way (like I successfully did 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.