views:

146

answers:

2

I have a set of numerical libraries in C++ and I want to call them interactively in a interpretive language like F# or IronPython.

So I have two choices now:

  1. Compile the library in native DLL and use PInvoke to call functions in it.

  2. Compile the C++ library to .Net dll using visual c++ (/clr:pure compile option).

The advantage of 1 is that it is very fast, however there are more work in it, e.g. I cannot PInvoke double pointer (e.g. float **), I must write another wrapper in the C++ library to make the interface friendly to .Net.

The advantage of 2 is that I don't need to do know Mashaling strings, arrays, etc. However, the .net dll is slower compared to the native one.

What others factors should be considered when choosing between the two?

+1  A: 

Have you measured the difference in speed? .net isn't as slow as people think it is -- once a .net app is loaded, it's usually jitted and often runs nearly as fast as if you'd compiled it as native code.

Also...marshaling ain't free. It tends to involve copying the data around, especially between app domains. Unless your libraries do massive amounts of work with little data passed back and forth, the cost of marshaling the data may negate any speed boost you'd get by making the library native.

There's only one foolproof way to answer the question: create a test program to use the library somewhat as you'd actually use it, compile the stuff both ways, and see which one's faster for you.

cHao
+1  A: 

From my experience with C++/CLI, it performs much better than PInvoke.

I have wrapped a lot of C code using C++/CLI and it works great.

It also has other benefits: The ability to use C++, the ability to create specific .NET interfaces that call the C functions and even to easily keep allocated unmanaged memory in the .NET classes. It also allows you to see the code coverage inside the unmanaged code when you write and run unit tests.

The only problem with C++/CLI is that it is a bit difficult to learn. It's a pretty complicated language since it has both all of the C++ features and all of the .NET features. Visual Studio doesn't treat it that nice like it does with C# and you don't have great tools Resharper to work with.

If you care about performance, I'm positive you'll find C++/CLI the right choice.

brickner