Jon Cage
Jon Cage

Reputation: 37458

Call C++ code from a C# application or port it?

I've recently been wrestling with an algorithm which was badly implemented (i.e. the developer was pulled off onto another project and failed to adequately document what he'd done) in C#.

I've found an alternative (from numerical recipes) which works but is written in C++. So I'm thinking probably the safest way to get something working would be to wrap the C++ up in a DLL.

Bearing in mind that I'm still a bit green when it comes to C# and have never tried making a DLL from scratch, does this sound like a reasonable approach (and if so, has anyone tried this / got any advice)? Or should I go the whole hog and try and port the C++ routine into C#?

Edit - I'm not looking for anyone to make the decision for me, but if anyone has any exprience of either route I'd be interested to hear their opinions and any nasty pitfalls that should be avoided. For example, how nasty is passing in lists of data from C# to a C++ STL vector?

Upvotes: 5

Views: 1245

Answers (4)

AnnaR
AnnaR

Reputation: 3186

I tried linking to c-dll's from c# code with quite good results, even though I had some problems sending data between the environments. Otherwise the procedure is quite straight forward. The more data you send back and forth (both amount and frequency) the slower your program will run, but you have probably already figured this out on your own.

The main drawback was maintaining the c#-c glue code (interface code) each time something changed or someone found a bug.

Here is a bit of code to get you started:

using System.Runtime.InteropServices;
    class myDllCaller {

       //call to function in the dll returning an int
      [DllImport("MyFavorite.dll")]
      private static extern int dllFunction(//list of parameters to function);

    public static void Main() {
    int rerult = dllFunction();

    }
}

Upvotes: 3

ChrisF
ChrisF

Reputation: 137148

It depends what your goals are.

If it's to have a working application I'd weigh-up the costs and benefits of both approaches and go with the most cost effective.

If it's to improve your C# then by all means rewrite the C.

Upvotes: 1

Rowland Shaw
Rowland Shaw

Reputation: 38130

If the C# version Mitch references isn't of a suitable licence for your purposes, You could use a managed C++ wrapper, that could reuse, and wrap the C code you have, but still be visible to your managed applications as a native .Net assembly. I've used this approach in the past for using the C API of a library that didn't have its own native .Net API, and found it relatively painless marshalling data between the two.

Upvotes: 2

Mitch Wheat
Mitch Wheat

Reputation: 300559

...Or you could download the already implemented code in C# from here.

Upvotes: 0

Related Questions