【问题标题】:calling F# functions from C# and getting null reference exceptions从 C# 调用 F# 函数并获取空引用异常
【发布时间】:2009-10-27 20:48:37
【问题描述】:

我正在使用安装了 2009 年 10 月 F# CTP 的 Visual Studio 2008。

我正在尝试从我的 C# 程序中调用一些 F# 代码。大多数类型的 F# 函数似乎都可以工作,但有些函数没有在 F# 中初始化,并且会抛出 NullReferenceExceptions。这样做的是闭包和部分应用的函数,即在 C# 中作为 FastFunc 类型出现的东西。

我做错了什么或忘记了什么,或者这可能是 F# 或 .NET 的错误?

下面的代码是为了演示这个问题。我实际上并没有尝试在实际应用程序中使用此代码。 此外,在 F# 中,一切正常。这是一个 F# 到 C# 的问题

F#:

namespace FS      
module FunctionTypes =

    //these all work in c# as expected
    let Value = "value"

    let OneParam (str:string) = str

    let TwoParam (str:string) (str2:string) = str + " " + str2

    let Lambda =
        fun () -> "lambda"  


    //these functions are null references in C#
    // they do work as expected in F# interactive mode
    let PartialApplication = TwoParam "what's up"

    let Closure = 
        let o = new System.Object()
        fun (i:int) -> o.ToString() + i.ToString()

    let ClosureWrapper (i:int) =
        Closure i  

C#(参考 F# 项目和 FSharp.Core)

 //these work as expected:
        var oneParam = FS.FunctionTypes.OneParam("hey");
        var twoParam = FS.FunctionTypes.TwoParam("yeah", "you");
        var lambdaFunction = FS.FunctionTypes.Lambda();
        var value = FS.FunctionTypes.Value;
        //  in the May09 CTP, Value returned null, 
        //      so it must have been fixed in Oct09 CTP



 //these do not work--each throws a NullReferenceException.
        var partial = FS.FunctionTypes.PartialApplication.Invoke("hello");
        var closure = FS.FunctionTypes.Closure.Invoke(1);
        var closureWrapper = FS.FunctionTypes.ClosureWrapper(1);

 //  FS.FunctionTypes.Closure itself is null, 
 //  so is FS.FunctionTypes.PartialAppliction.
 //  FS.FunctionTypes.ClosureWrapper is a regular function, 
 //    but it calls Closure, which is null     

【问题讨论】:

  • F#代码是编译成.exe还是.dll?
  • @Brian 它已编译为 .dll。设置是同一解决方案中的两个项目,其中 C# 项目引用 F# 项目。
  • 它现在应该显示为 FSharpFunc 而不是最后一个 CTP 的 FastFunc。
  • 我无法复制这个。我真的认为您的 C# 引用的是 F# .exe 而不是 F# .dll。
  • @Brian 你是对的。我的 F# 项目的输出类型是控制台应用程序,而不是我想象的类库。我想这可以解释它。谢谢

标签: c# f# closures fastfunc


【解决方案1】:

它对我有用,我得到“你好”、“System.Object1”、“System.Object1”用于部分、闭包和closureWrapper vars。您是否引用了好的 FSharp.Core 程序集?

【讨论】:

  • @Stringer Bell 是的,我指的是 FSharp.Core。问题是我的 FSharp 项目正在编译为一个 exe……现在一切都在为我工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 2015-09-23
  • 1970-01-01
  • 2013-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多