You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.

Unmanaged Interop

While the .NET platform offers a wealth of functionality and is a great platform for writing new applications, there are many times when you will want to interoperate with legacy code: for example, calling into frameworks written in C or C++.

F# supports all the same mechanisms as C# for interoperating with unmanaged code.

Platform Invoke

Platform invoke, also referred to as P/Invoke, is how managed applications can call into unmanaged libraries, such as Win32 API functions. When you have a non-.NET library you wish to call into, P/Invoke is how you do it.


P/Invoke isn’t limited to just Windows. Any CLI implementation, such as Mono, may use P/Invoke in order to access libraries outside of the CLI runtime environment.

In F#, to make a P/Invoke call, you must first declare the function signature. This means defining the function signature so that the .NET framework knows how to call into it correctly (the library where the function exists, the number and types of parameters, and so on).

Example B-4 shows calling into the Win32 function CopyFile, defined in the library kernel32.dll. The DllImport attribute shows which library and the name of the method the F# function is bound to. After that the function is declared using the extern keyword followed by the function signature as it would be declared in a C-like language. (Types coming before parameter names.)

Once the P/Invoke signature is declared, the actual function can be called like any normal F# function value. ...

The best content for your career. Discover unlimited learning on demand for around $1/day.