Embedding standard C++ into a .NET application
I want to write an algorithmic library in standard, platform-independent C++.
Can I then开发者_StackOverflow中文版 take the same C++ code and compile it for .NET so that a C# application can use the library? If not, what is the easiest way to achieve this kind of interop?
You cannot directly interface between C# and standard C++. However, you can use your C++ library inside a C++/CLI wrapper which makes the functionality available in .NET managed code (and thus C#).
Simply write the wrapper as a C++/CLI library that exposes a .NET API and includes the code from your standard C++ library (but unfortunately this cannot be statically linked, as far as I know).
You have three ways to expose your library to easily be called from managed code:
- write a C++/CLI wrapper for it that contains a
public ref class
- the C# code will call methods of this class, which will call native methods of your library - expose a C-style function from your library as a DLL - the C# code will use P/Invoke to call the function
- write a COM component in C++ that uses your library and call it from the C# code by adding a COM reference to it.
That third one, COM, I include only for completeness. It wouldn't be my first choice. Or my third. It's one thing if the COM component exists, it's another to write it just for this.
Between the first two it's a matter of who else might use this library. If the C# code is the only one using it, do what you like. But for example you might have 15 or 20 native methods that set various properties, followed by a go
or execute
method that does the actual work. Because managed-native interop has a cost, I would tell you to write one C++/CLI function that takes 20 parameters, calls the various native functions and then calls the go
or execute
. This gives you a chunkier interface instead of chatty and reduces your interop costs.
You can call native C/C++ libraries from any .NET language using pinvoke. Here's a quick tutorial from MSDN. You can also create a COM dll in C++ that you can reference directly from within C# using COM Interop. Unless you need the advantages of COM, pinvoke is a much easier route to go.
And of course, as Konrad stated, you wrap the C++ dll using a managed C++ solution.
As an example, check out http://www.pinvoke.net/ for samples on how you call win32 api's from C#.
From the MSDN link above (modified per the comment below):
using System;
using System.Runtime.InteropServices;
class PlatformInvokeTest
{
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int puts(
[MarshalAs(UnmanagedType.LPStr)]
string m);
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
internal static extern int _flushall();
public static void Main()
{
puts("Hello World!");
_flushall();
}
}
精彩评论