Jun 26

C# from F# ? using C# and the .NET APIs from F#

Assemblies written in C# and other .NET languages can be directly accessed from F#. This makes F# an amazingly powerful language given the huge number of libraries available. This section describes how to use various .NET constructs from F#. A working knowledge of C# or another .NET language is assumed.

Longer examples of interoperability can be found in the samples that come with the F# compiler.

The Basics

Types.

Jun 26

Using F# Interactive (FSI.EXE)

Jun 26

Compiler Installation

  • Uninstall any old release of F#. Simply delete the directory contents.
  • Unzip the FSharp-ILX-VERSION, e.g. at Desktop (the directory FSharp-ILX-VERSION will be created automatically).
  • Double-click and run FSharp-ILX-VERSION\InstallFSharp.msi
  • InstallFSharp.msi may fail if .NET 2.0 is not installed. If so, run alternative-install.bat.
  • Delete the unzipped files, keeping the ZIP for archive if necessary.

    InstallFSharp.msi (and also alternative-install.bat) install the F# libraries in the Global Assembly Cache (GAC) in your machine, which means you can run the programs you compile from anywhere. Several flavours of these library may get installed, e.g. for use with early versions of the .NET Common Language Runtime (e.g. fslib10.dll - the ‘10′ stands for ‘version 1.0 or version 1.1′). F# will select the appropriate library based on the command line switches you use. You may install the libraries on other machines by copying appropriate files and running the alternative-install.bat script there or just manually adding the DLLs to the GAC

Installing F# Editing for Microsoft Visual Studio 2005

First follow the steps under Compiler Installation. If installing InstallFSharp.msi succeeded then you are done!!. See also Debugging with Visual Studio and Using F# Interactive with Visual Studio.

If InstallFSharp.msi failed you can try a manual install by simply running alternative-install-vs2005.bat. Indeed, you can always use this technique if you wish, but there will be no uninstall option. If this fails see the troubleshooting section below.

Installing F# Editing for Microsoft Visual Studio 2003

If you have Visual Studio 2003, you must do a manual install by simply running alternative-install-vs2003.bat. There is no uninstall option when using this technique, though you can always upgrade an installation simply by re-registering (in truth you can uninstall by just running the regsvr32 /u uninstallation commands that reverse the registrations done in the batch file).

When installing for Visual Studio 2003 you should ensure your machine is up-to-date with latest service packs and updates from Microsoft. You may also need to install the Microsoft Visual C++ 2005 runtime redistributable. Some people have reported problems running InstallFsharp.msi when installing for Visual Studio 2003 when registering DLL such as fslangservice.dll, in which case you can ignore these errors and register these DLLs using alternative-install-vs2003.bat. After doing this you should run devenv /setup, if this has not been done automatically by alternative-install-vs2003.bat.

Known Issues with F# Editing for Visual Studio

Here are the known issues in F# for Visual Studio, which you should read before making serious use of the system.

  • Dependency order is required for the files in the Solution Explorer. If they aren’t, unload the project (right click on project, unload), edit the project file (right click on project, edit), put the entries in dependency order, reload project file.
  • Resources, lexers, parsers etc. cannot be compiled from Visual Studio. You may wish to create a VB or C# project to hold your resource files.
  • Use -R command line options in your project properties to reference across projects. This will copy the relevant files locally.
  • Only opened files are typechecked interactively. That is, if an error is lurking in a closed file you won’t see that until you use F# Interactive or build and run.
  • A couple of errors are only reported during code generation, so they don’t show up as red-squigglies in Visual Studio
  • Errors in earlier files can lead to errors in later files. You should have the ‘Errors’ Window open to spot the global view of errors in your file.
  • Some errors lead to potentially misleading confusing cascading errors (up to the maximum of 10)
  • Sometimes the typechecker thread is a little behind the editing thread, and occasionally doesn’t catch up. To prompt the typechecker thread into action simply do a fake edit on the file (e.g. by hitting ’space’ then undo)
  • Interactive typechecking happens against the _saved_ copies of files. That is, if you change a dependent file, that won’t be reflected in the interactive type checking of subsequent modules until you save it, AND you have to prompt the re-typecheck of the dependent files, (e.g. by hitting ’space’ then undo)
  • The popdown menus for intellisense when hitting “|” were confusing and tiresome in versions prior to 1.1.10.2. This has now been disabled until we get the interaction right.

Troubleshooting installations of F# for Visual Studio

  • You can check if F# for Visual Studio was successfully installed by running ‘regedit.exe’ and looking to see where the package key {771D2A70-00A2-4E42-9440-425CD92A4116} appears (use the Find menu). A successful installation into Visual Studio 2005 without VSIP would place it under
    HKEY_LOCAL_MACHINESOFTWAREMicrosoftVisualStudio8.0Packages

    An installation in VS 2003 would change 8.0 to 7.1, and if using the VSIP SDK then add ‘Exp’. (e.g. 7.1Exp and 8.0Exp). If the key doesn?t occur at all then installation of the F# Visual Studio components failed. If so, please report this problem to [email protected]

  • You can force F# to be installed into a particular version of Microsoft Visual Studio by using the following environment variable settings. These must be set GLOBALLY, i.e. using ‘My Computer’->’Advanced’->’Environment Variables’, before you run FsVsPkgsInstaller.msi. You should unset this environment variable after you uninstall F#.
    • FSHARP_TARGET_VS_VER=7.0 — install into Microsoft Visual Studio .NET, normal mode, or no VSIP
    • FSHARP_TARGET_VS_VER=7.0Exp — install into Microsoft Visual Studio .NET, VSIP experimental mode
    • FSHARP_TARGET_VS_VER=7.1 — install into Microsoft Visual Studio 2003, normal mode, or no VSIP
    • FSHARP_TARGET_VS_VER=7.1Exp — install into Microsoft Visual Studio 2003, VSIP experimental mode
    • FSHARP_TARGET_VS_VER=8.0 — install into Microsoft Visual Studio 2005, normal mode, or no VSIP
    • FSHARP_TARGET_VS_VER=8.0Exp — install into Microsoft Visual Studio 2005, VSIP experimental mode
  • If necessary you can de-register the F# package from particular versions of VS by running ‘regedit.exe’ and looking to see where the package key {771D2A70-00A2-4E42-9440-425CD92A4116} appears (use the Find menu). Delete all such registry keys and all sub-entries. Visual Studio will then no longer be able to load the F# packages.

Debugging F# code using Microsoft Visual Studio 2003 and 2005

The Visual Studio Debugger will work with F# code without any additional installation steps. Debugging information for the libraries may be found in the bin directory. In Visual Studio 2005 you may need to disable “Just My Code” debugging (use the “Options” menu). You can also set the appropriate symbol path there or you can add that path to the _NT_SYMBOL_PATH environment variable.

 
F# Interactive is the name of the command line interactive shell for F#. It runs on .NET 2.0 (Visual Studio 2005), .NET 1.x (Visual Studio 2003) and Mono. You can also use it as a tool window in Visual Studio 2005. Run it using bin\fsi.exe. The WebCrawl, TermWalker and DirectX 3D Demo give examples of how to script. Note you can paste line-by-line into the top-level environment, or else use F# Interactive in Visual Studio or another shell-hosting environment such as those available in Emacs. You can also often compile scripts using fsc.exe.

Inputs to fsi.exe are terminated with ;; (nothing happens until you type this!). You generally don’t need to enter this when using F# from Visual Studio as it is added automatically each time you send text for execution. This applies particularly when using the light syntax option syntax #use ;; load the given file as if it had been entered from the command line #load ;; compile the given file as a named module, then load #time;; toggle timing on/off. #quit;; quit the session.

The first three of these can also be used directly in F# source code files. It is also handy to quote filenames using ‘verbatim strings’, e.g.

    #r @"c:Program Filesfsharp-ILX-VERSIONbinabsil.dll";;

When you type an expression into F# Interactive, the last such expression is assigned into the variable it. This is purely an artefact of typing entries into F# Interactive. If you compile the same code with the command-line compiler or when loading a file into F# Interactive as a compilation unit the expression will simply be executed and its result discarded.

Using F# Interactive in Visual Studio

F# comes with a Visual Studio AddIn that lets you use ‘F# Interactive’ for use as a tool Window in Visual Studio 2005. The tool window is a Visual Studio AddIn, and should be managed via the AddIn Manager menu option found under the ‘Tools’ menu. You can also start up F# Interactive simply using ‘Alt-Enter’ (Note: this key must currently be bound manually on the Japanese edition of Visual Studio 2005)

To start the session, go to the AddIn manager and select ‘F# Interactive for Visual Studio’. If it is already selected, then unselect it, close and reopen the AddIn manager and reselect it. Either way a new window should appear with an F# Interactive session.

The session is global to the instance of Visual Studio and text can be sent from any F# source code file (.fs, .fsi, .ml, .mli). Use the ‘Alt-Return’ combination to evaluate selected text, and ‘Alt-Quote’ (i.e. Alt-’) to evaluate the current line of text without selecting it. History is available with the up/down arrows. These shortcuts may change in future releases.

File names are resolve relative to the scripts containing the reference. Visual F# Interactive sets the line and directory context of the session each time an entry is sent from Visual Studio.

To troubleshoot an installation:

  • Check fsi.exe starts up at the command prompt, including entering simple programs.
  • Check the ‘bin’ directory of your F# installation (e.g. FSharp-ILX-VERSION\bin) is listed in the entries in your AddIn search path under ‘Tools’, ‘Options’ in Visual Studio.

F# Command Line - using the compiler

The fsc.exe compiler is a traditional command-line compiler with a set of command-line options similar to both the OCaml compiler and the C# compiler. Detailed help can be found by running “fsc — help”. Some of the common command-line flags are shown below, along with detailed instructions on the How to statically link the F# libary using the “–standalone” option. Also see the notes on using F# in conjunction with alternative CLI implementations.

The most common command-line options (FSC.EXE)

  • -o Name the output file.
  • -I Specify a directory for the search path for referenced assemblies.
  • -g Produce debugging information.
  • -O3 Turn on maximal optimization.
  • -a Produce a DLL.
  • -r Reference an F# or .NET DLL.
  • –keyfile Sign an assembly using the given keyfile. This must be done when creating DLLs that will be shared by multiple programs and installed in the “Global Assembly Cache” on target machines.