代码之家  ›  专栏  ›  技术社区  ›  dan

从C调用F函数并获取空引用异常

  •  2
  • dan  · 技术社区  · 15 年前

    我正在使用安装了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     
    
    1 回复  |  直到 15 年前
        1
  •  2
  •   elmattic    15 年前

    它对我有效,我得到了“你好”,“system.object1”,“system.object1”,用于部分、闭包和闭包包装器变量。您是否引用了良好的fsharp.core程序集?