开发者

How to share a class in a Visual C++ DLL with C#?

I wrote my program in C++ and exported it as a DLL. I have a C# WPF GUI and I want to import the DLL to do the processing.

I am very new to C#. How can I use the C++ class in C#? I know I can't just use the .h file.

Because I used pointers in C++, in C# I couldn't use pointers. That's why I got confused. Like in C++ i used char* instead of string, and I need to return double* for a big collection of 开发者_如何学Pythondouble data, and things like that.


There are a number of ways:

  1. Export the DLL functions and use DllImportAttribute to P/Invoke into the DLL.
  2. If it is a COM DLL, then you can generate a Runtime Callable Wrapper via TLBIMP.exe
  3. You can use C++/CLI to build create a .Net assembly which loads and calls methods on the DLL natively.

To address your additional concerns, yes, you can use pointers in C#. If you have a function which has a double* parameter, you can declare that in C# like this:

[DllImport("Your.DLL")]
private static extern unsafe void DoProcessing(double* data, int dataSize);

You need to make sure you check the "Allow Unsafe Code" checkbox on the build tab of the C# project, and after that, you can use pointers to your heart's content.

However, note that while I'm providing the pointer signature here, since you are obviously comfortable with pointers, there are other signatures which could be more safe for you to use, and would not require you to compile C# with unsafe code. The standard marshaller in the CLR will take care of the conversion from a pointer to a C# array, provided you give it a bit of a hint if the length is required:

[DllImport("Your.DLL")]
private static extern void DoProcessing(
        [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] double[] data, 
        int dataSize);

This instructs the marshaller to use the parameter at index 1 (the 2nd parameter) as the size of the array of doubles pointed at by the 1st parameter. This allows you to avoid pointers in C#, and use safe CLI types. However, if you like pointers, my advice is to just use them - the C# will be easier for you than having to figure out how to write the method signature without them.

For more details on P/Invoke, refer to this documentation: http://msdn.microsoft.com/en-us/library/aa288468(VS.71).aspx


A lot depends on the structure of your C++ dll. If you have just a handful of functions, and they are not member functions of a class, then you can make them "extern C" functions and use the P/Invoke capability in .NET (sometimes called DllImport because of the attribute you use) to access the functions from C#.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜