7

I've got a C# extern declaration that goes like this:

    [DllImport("something.dll")]
    public static extern ReturnCode GetParent(IntPtr inRef, out IntPtr outParentRef);

How to translate that to F#?

Dax Fohl
  • 10,654
  • 6
  • 46
  • 90

3 Answers3

13

You can try something like the code below. I don't know what ReturnCode is, so the code below expects it is an integer. For any more complex type, you'll need to use [<Struct>] attribute as in the answer referenced by A-Dubb.

type ReturnCode = int

[<System.Runtime.InteropServices.DllImport("something.dll")>]
extern ReturnCode GetParent(System.IntPtr inRef, System.IntPtr& outParentRef);

To call the function, you'd write something like this:

let mutable v = nativeint 10
let n = GetParent(nativeint 0, &v)

BTW: Could you also post a sample C code that implements the function in something.dll? If yes, we could try running the solution before sending an answer...

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • that works great! However - the old C# declaration allowed me to do "let (n, v) = GetParent input". Any way to modify the code to allow that syntax? – Dax Fohl Jul 02 '11 at 19:15
  • oh, and ReturnCode is just an enum based off uint32 – Dax Fohl Jul 02 '11 at 19:33
  • Seems to be related to the "hidebysig" decorator in CIL. In red gate reflector the C# method has it, whereas the F# method does not. Does F# offer hidebysig? (I'm still trying to figure out what that even means). – Dax Fohl Jul 02 '11 at 20:04
  • @Dax - I'm not sure if there is any way to get the nice syntax (could be related to some F# meta-data - the compiler might allow the syntax only on external definitions). I'm not sure it has something to do with hidebysig (afaik that's something to do with hiding or overloading). – Tomas Petricek Jul 03 '11 at 00:35
1

For anyone else trying to use F# with EnvDte via PInvoke this may help:

[<System.Runtime.InteropServices.DllImport("ole32.dll")>] 
extern unit CreateBindCtx(System.IntPtr inRef, IBindCtx& outParentRef);
[<System.Runtime.InteropServices.DllImport("ole32.dll")>]
extern unit GetRunningObjectTable(System.IntPtr inRef, IRunningObjectTable& outParentRef);

which apparently is slightly incorrect, but appears to work. the definition should be:

[<System.Runtime.InteropServices.DllImport("ole32.dll")>] 
extern int CreateBindCtx(System.IntPtr inRef, IBindCtx& outParentRef);
[<System.Runtime.InteropServices.DllImport("ole32.dll")>]
extern int GetRunningObjectTable(System.IntPtr inRef, IRunningObjectTable& outParentRef);
Maslow
  • 18,464
  • 20
  • 106
  • 193
1

Maybe this similar question will point you in the right direction. Looks like he used attributes at the parameter level for "in" and "out" F# syntax for P/Invoke signature using MarshalAs

Community
  • 1
  • 1
A-Dubb
  • 1,670
  • 2
  • 17
  • 22