P/Invoke tries to make your life easier by automatically converting (“marshalling”) data types from managed code to native code and the other way around.
Sometimes a C/C++ function needs to store data you pass to it for later reference. If such data is a managed object (like a
class) you need to make sure that the garbage collector doesn’t delete it while it’s still used/stored in the native code.
That’s what pinning is for. It prevents the garbage collector from deleting and moving the object.
In the previous tutorial we passed a single string to a native C/C++ function by using P/Invoke.
This function was defined like this:
// C++ void print_line(const char* str);
// C# [DllImport("NativeLib.dll")] private static extern void print_line(string str);
However, there exists a hidden pitfall here:
What happens when the user passes a non-ASCII character to this function?
P/Invoke is a way of calling C/C++ functions from a .NET program. It’s very easy to use. This article will cover the basics of using P/Invoke.
Note: This tutorial will focus on Windows and thus use Visual Studio. If you’re developing on another platform or with another IDE, adopting the things in this article should be easy enough.