简体   繁体   中英

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

I've recently been wrestling with an algorithm which was badly implemented (ie 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?

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();

    }
}

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.

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.

...或者你可以从这里下载已经实现的C#代码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM