Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any ideas how to integrate F# code with native C++?

Tags:

c++

.net

f#

managed

I want to use some F# code in native C++. More precisely, I want to write some data structures in F# and then use them in my C++ code.

I have no idea how can I mix managed F# with unmanaged C++. How can I create a glue layer?

like image 534
Oleksandr Karaberov Avatar asked Mar 02 '13 23:03

Oleksandr Karaberov


1 Answers

One way is to create an assembly in C++/CLI which will be mixed mode assembly that can reference your F# assembly and export native symbols at the same time, so they can be used in native c++ library later. This option is the most versatile. You can use this method to create 'bridges' which work both ways.

One approach I like to use when I do this (and I've done this to include C#, Wpf based GUI inside another native, c++/mfc application) is to create simple C-bindings, like this:

//C++
void Method1() { Bridge::Method1(); }
void Method2(int param, int* nativeArray) 
{ 
    array<int>^ managedArray = marshalArray();
    Bridge::Method2(param, managedArray);
}
....

//C#
static class Bridge
{
    public static void Method1() { ... }
    public static void Method2(int param, int[] ar) { ... }
}

This basically allows you to keep your C++/CLI wrapper as small as possible, leveraging whole code to managed library, as well as allowing you to use this library from C and even dynamically load it with LoadLibrary().

Some might say this is an overkill (you do write some a bit of plumbing code twice) though.

If you want to do something crazy you can also try and export single methods from you F# library directly, basically making it a mixed-code assembly, as described in article Simple method of dll export without C/CLI

like image 173
Marcin Deptuła Avatar answered Sep 20 '22 17:09

Marcin Deptuła