f#中的COM组件

时间:2011-03-31 16:04:44

标签: com f# .net-2.0

我是C ++开发人员,他必须在F#中编写COM组件。该组件应该在具有.NET 2.0的系统上运行。 IDE是Visual Studio 2010.我是.NET和F#的新手。我想要一个这个组件的简单示例。


更新 感谢Daniel指定方向。这是我对这个问题的回答。

namespace COM_FS
open System
open System.Runtime.InteropServices

[<Guid("6E6864CC-5FB7-44B8-B6E3-A5291C9B4AC8")>]
type IExampleFS = interface
  abstract SetString : string -> unit
  abstract GetString : unit -> string
end

[<Guid("01A11F64-59E1-496F-989F-7E0CC5CE8570");
ClassInterface(ClassInterfaceType.None);
ComVisible(true)>]
type ExampleFS_Class = class
  val mutable str : string
  new () = { str = null }
  interface IExampleFS with
    member this.SetString(x) = this.str <- x
    member this.GetString() = this.str
  end
end

我必须将AssemblyInfo.fs添加到同一AssemblyInfo.cs

namespace COM_FS

open System.Reflection
open System.Runtime.CompilerServices
open System.Runtime.InteropServices

module AssemblyInfo =
  [<Literal>]
  let public Version = "1.0.0.0"
  [<Literal>]
  let public FileVersion = "1.0.0.0"

[<assembly: AssemblyTitle("COM_FS")>]
[<assembly: AssemblyDescription("")>]
[<assembly: AssemblyConfiguration("")>]
[<assembly: AssemblyCompany("Mycrosoft")>]
[<assembly: AssemblyProduct("COM_FS")>]
[<assembly: AssemblyCopyright("Copyright © Mycrosoft 2011")>]
[<assembly: AssemblyTrademark("")>]
[<assembly: AssemblyCulture("")>]


[<assembly: ComVisible(true)>]
[<assembly: Guid("39ADA032-BF0F-45C9-BE4A-66AD14352F63")>]

[<assembly: AssemblyVersion(AssemblyInfo.Version)>]
[<assembly: AssemblyFileVersion(AssemblyInfo.FileVersion)>]
()

客户端C ++代码看起来像

COM_FS::IExampleFSPtr p(__uuidof(COM_FS::ExampleFS_Class));

_bstr_t str(L"world");
p->SetString(str);
wchar_t* wstr = p->GetString();
std::wcout << wstr << std::endl;

1 个答案:

答案 0 :(得分:3)

您可以从C#示例一对一地翻译界面,语法上只有很小的差异。它主要是(完全?)应用属性的问题。除此之外,它与编码其他任何内容没什么不同。

<强>更新

假设this article是正确的,这里是语法的采样器:

open System.Runtime.InteropServices

[<Guid("694C1820-04B6-4988-928F-FD858B95C880")>]
type DBCOM_Interface =
    [<DispId(1)>]
    abstract Init : userid:string * password:string -> unit
    //...

[<Guid("47C976E0-C208-4740-AC42-41212D3C34F0"); InterfaceType(ComInterfaceType.InterfaceIsIDispatch)>]
type DBCOM_Events = interface end