PInvoke or using / clr: clean to compile

I have a bunch of number libraries in C ++ and I want to call them interactively in an interpretation language like F # or IronPython.

So, I have two options:

  • Compile the library into a native DLL and use PInvoke to call functions in it.

  • Compile the C ++ library to .Net dll using Visual C ++ (/ clr: clean compilation).

Advantage 1 is that it is very fast, however it has more work to do, for example. I can't use PInvoke double pointer (like float **), I have to write another wrapper in the C ++ library to make the interface friendly .Net.

Advantage 2 is that I don't need to know Mashaling strings, arrays, etc. However DLL.net is slower compared to the original one.

What other factors should be considered when choosing between them?

+2


a source to share


2 answers


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 advantages: the ability to use C ++, the ability to create specific .NET interfaces that call C functions, and even easily store allocated unmanaged memory in .NET classes. It also allows you to see code coverage within unmanaged code as you write and run unit tests.



The only problem with C ++ / CLI is that it is a little difficult to learn. It is a rather complex language as it has all the features of C ++ as well as all the features of .NET. Visual Studio doesn't treat it as well as it does C # and you don't have great Resharper tools to work with.

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

+1


a source


Have you measured the difference in speed? .Net is not as slow as people think it is - once a .net application is loaded, it usually crumbles and often runs almost as fast as if you compiled it as native code.

Also ... marshaling is not free. This tends to involve copying data, especially between application domains. Unless your libraries are doing a huge job with small data going back and forth, the cost of marshaling the data can negate any speed boost you get by building your own library.



There is only one reliable way to answer the question: create a test program to use the library multiple as you used it, compile the stuff both ways and find out which one is faster for you.

+1


a source







All Articles