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.
For this tutorial, we need a small project structure containing two projects:
- NativeLib : a C++ library project
PInvokeTest : a C# console project
- Simple P/Invoke
- Unable to load DLL
- Stack Imbalance
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);
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?
- ASCII and Unicode: A Historical Overview
- P/Invoke String Conversions
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.
Marshalling Primitive Data Types
- Marshalling Strings
- Marshalling Arrays
- Marshalling Objects
- Marshalling Structs
- Marshalling Arbitrary Pointers
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 in use/still stored in the native code.
That’s what pinning is for. It prevents the garbage collector from deleting and moving the object.
- Pinning an Object
- Passing a Pinned Object
- Pinning and Passing Strings
- Verifying the Pinned Object is passed
I thought this a great series on P/Invoke and one that covers areas that might not have been covered by others...
Related Past Post XRef:
“I got your P/Invoke… right here…” But is it right?
.Net, Native, P/Invoke marshaling just like magic… “Marshaling with C# Pocket Reference” (Think “Marshalling Guide for the Busy Dev Guy”)
Signature/Data Type Conversion P/Invoke Cheat Sheet – aka What do you convert a wChar_t to .Net?
Marshall Fixed Length TCHAR Strings between Managed and Unmanaged Code