ahala
ahala

Reputation: 4803

F# function to be used in c# library : delegate with byref type

I have a c# dll library with one method g accepting the following function f in C# as an input

 void f(double[] x, ref double func, double[] grad, object obj)

In the function body, both func and grad values are updated. The input signature of g(f) in F# reads

f:float[]-> byref<float> -> float[]-> obj->unit

how can I write f in f# to use g(f) in f#?

EDIT when I follow ildjarn's answer below like

let f(x:float[]) (func:byref<float>) (grad:float[]) (obj: obj) = 
    func <- ...
    grad.[0] <- ... 
    grad.[1] <- ...
    ...
    ()

I got error on g(f) with

This function value is being used to construct a delegate type whose signature includes a byref argument. You must use an explicit lambda expression taking 4 arguments.

what should I do to make it work? thanks. UPDATE: it turns out I have to use g(fun (x:float[]) (func:byref<float>) (grad:float[]) (obj: obj) -> .... Cannot give the inside function a name like f.

Upvotes: 3

Views: 648

Answers (2)

Yin Zhu
Yin Zhu

Reputation: 17119

A canonical way to expose F# functions to other .NET language is to use a class, sometimes a static class, e.g. the design of the LChart library (link):

Excel Financial functions for .NET is a project written in F#, and is a general .NET library. You can see how its public API is written. You can also learn how to link the FSharp.Core.dll to the dll so that the target machine does not need to install F# runtimes.

Update:

ref double func is translated to f# as let y = ref (func), double[] grad is just float[] in F#. See the following example for the ref:

public class tt
{
    public static void temp(int x, ref double[] y)
    {
        y = new double[10];
        y[1] = 10;
    }
}

in F#:

    let y = ref (Array.create 10 0.0)
    tt.temp(0, y)
    printfn "%A" y
    0

Notice that the second parameter of temp is a ref type. You simply create a ref handle for the array object by using ref operator in F#.

Upvotes: 1

ildjarn
ildjarn

Reputation: 62995

let function1 (x:double[], func:byref<double>, grad:double[], obj:obj) = ...

Upvotes: 1

Related Questions