Tutorial needed on invoking unmanaged DLL from C#.

2019-08-02 01:20发布

问题:

I have a DLL from a vendor that I Need to invoke from C#. I know that C# data classes are not directly compatible with C++ data types.

So, given that I have a function that receives data and returns a "string".

(like this)

string answer = CreateCode2(int, string1, uint32, string2, uint16);

What must I do to make the input parameters compatible, and then make the result string compatible?

Please - I have never done this: Don't give answers like "Use P/Invoke" or "Use Marshal" I need a tutorial with examples.

All the P/Invoke examples I have seen are from .NET Framework 1.1, and Marshall (without a tutorial) is totally confusing me.

Also, I have seen some examples that tell me when I create my extern function to replace all the datatypes with void*. This is makes my IDE demand that I use "unsafe".

回答1:

This isn't quite a tutorial but it's got a lot of good information on using P/Invoke Calling Win32 DLLs in C# with P/Invoke
It'll give you an idea of the terminology, the basic concepts, how to use DllImport and should be enough to get you going.

There's a tutorial on MSDN: Platform Invoke Tutorial.
But it's pretty short and to be honest the one I've mentioned above is a much better source of information, but there's a lot of it on there.

Also useful is the PInvoke Signature Toolkit, described here .
And downloadable here.
It lets you paste in an unmanaged method signature, or struct definition and it'll give you the .NET P/Invoke equivalent. It's not 100% perfect but it gets you going much quicker than trying to figure everything out yourself.

With regards to Marshalling specifically, I would say start simple. If you've got something that's some sort of pointer, rather than trying to convert it directly to some .NET type in the method signature using Marshal it can sometimes be easier to just treat it as an IntPtr and then use Marshal.Copy, .PtrToString, .PtrToStructure and the other similar methods to get the data into a .NET type.
Then when you've gotten to grips with the whole thing you can move on to direct conversions using the Marshal attribute.

There's a good 3 part set of articles on marshalling here, here and here.