Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a COM object in F#

Tags:

f#

com

I need IMessage Interface. In C# I could write

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

but when I try to do this in F#

let oMsg = new CDO.Message()

I get an error message:

'new' cannot be used on interface types. Consider using an object expression '{ new ... with ... }' instead.

How to solve this problem?

like image 434
Oleg Leonov Avatar asked May 14 '16 11:05

Oleg Leonov


People also ask

What is a COM Object C++?

A COM object is an instance of a coclass in memory. Note that a COM "class" is not the same as a C++ "class", although it is often the case that the implementation of a COM class is a C++ class. A COM server is a binary (DLL or EXE) that contains on or more coclasses.

What is an object expression C#?

An object expression is an expression that creates a new instance of a dynamically created, anonymous object type that is based on an existing base type, interface, or set of interfaces.


1 Answers

You need to use the version that has 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 explicitly had to add a reference to Microsoft ActiveX Data Objects 6.0 Library to the project to make the object instantiation work.

In case you want to use the specific interface and not the Co-Class (as proposed by Hans Passant), use this version that casts 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 
like image 93
NineBerry Avatar answered Nov 02 '22 21:11

NineBerry