How to create a COM object in F #

I need an IMessage interface. In C #, I could write

CDO.Message oMsg = new CDO.Message(); // ok 

but when i try to do it in f #

 let oMsg = new CDO.Message() 

An error message appears:

'new' cannot be used for interface types. Instead, consider using the object expression '{new ... with ...}'.

How to solve this problem?

+6
source share
1 answer

You need to use the version with the class added to the interface name:

 open System [<EntryPoint>] [<STAThread>] let main argv = let oMsg = new CDO.MessageClass() oMsg.Subject <- "Hello World" Console.WriteLine(oMsg.Subject) Console.ReadLine() |> ignore 0 

Note. I also had to add a link to the Microsoft ActiveX Data Objects 6.0 Library in the project in order to instantiate the object.

If you want to use a specific interface, not Co-Class (as suggested by Hans Passant), use this version, which adds the created Co-Class to the interface, thereby returning a pointer to the actual interface.

 open System [<EntryPoint>] [<STAThread>] let main argv = let oMsg = upcast new CDO.MessageClass() : CDO.IMessage oMsg.Subject <- "Hello World" Console.WriteLine(oMsg.Subject) Console.ReadLine() |> ignore 0 
+8
source

All Articles