Wed Dec 17 2025
The Advantages of C# Interop for Plugin Development in C/C++ Applications
C/C++ application plugins usually get code loaded into the process through module injection, then operate on the memory, objects, and functions inside the program. This usually requires a fairly low-level language. At the same time, we want plugin development to stay as simple as possible. C/C++ keeps memory consistency well, but it places high demands on code development and is often unstable.
C#, as a high-level language, introduced the concepts of managed and unmanaged from the start. It has good memory interoperability, so besides the reduced development burden that comes with a high-level language, you also get fairly comfortable memory consistency support.
Structs
The most common memory layouts in C/C++ come from structs. C# also has native struct support, declared with the struct keyword.
Generally, as long as certain conditions are met (all fields are non-nullable unmanaged types), a struct can be an unmanaged type. Unmanaged types are allocated directly on the stack and don't go into the managed heap. Copies are usually value copies, not reference copies. Value types can be passed by reference through an explicit ref, and ref passing also lets you write chained field modifications. Functions can use the unmanaged generic constraint to restrict incoming types to unmanaged types.
For ref variable operations, also note that if assignment passing happens, the type on the left must be ref var to explicitly declare reference passing; otherwise the default value passing occurs.
C# pointers can also be applied to value types. You can directly convert an nint pointer to an unmanaged type pointer, then convert it to a ref through Unsafe methods for operations. (Or just use pointer operators directly inside an unsafe block.) The programming experience here is similar to C/C++.
C# ref struct is a more strictly restricted struct. It requires the struct to be allocated only on the stack. A typical example is Span<T>. It's a type provided in the C# standard library for high-performance access to contiguous memory, and by design it lets developers implement high-performance zero-copy operations more easily.
From the perspective of plugin framework API design, if you want to provide users with an unmanaged struct but wrap part of the access (wrapping a pointer as a ref that can be operated on in safe code, indexers, etc.), you can wrap it elegantly with C# property syntax.
There are also some limitations to achieving memory consistency. C++ lets you write complex multiple inheritance and const template generics. C# structs forbid inheritance. You can lay out memory through field composition, but in practice we usually don't choose to wrap overly complex structs.
C# provides attributes such as [StructLayout] and [FieldOffset] that let you precisely control how struct fields are laid out in memory. In particular, you can declare the same FieldOffset for multiple field types to simulate the union data type from C structs.
Pitfalls
There are also some pitfalls in memory layout that you might fall into. One example to watch out for is that C# strings use UTF-16 characters internally. So when working with C-style strings, you need to use methods like Marshal.PtrToStringUTF8.
The Pack field of C# StructLayout attribute lets you control how fields inside a struct are aligned in memory. But there's currently no way to align stack address allocation for structs. This means that on Linux, some SIMD optimized instructions require the passed address to be 16-byte aligned; passing a plain stack pointer will cause a crash. C# provides the NativeMemory.AlignedAlloc method for aligned memory allocation. For example, NativeMemory.AlignedAlloc(256, 16); allocates a 16-byte-aligned, 256-byte memory block.
Example
A simple vector implementation:
[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 12)]
public struct Vector3
{
public float X;
public float Y;
public float Z;
}
Equivalent to:
float* vec = stackalloc float[3];
If you need 16-byte aligned memory allocation:
var ptr = NativeMemory.AlignedAlloc((nuint)sizeof(Vector), 16);
Calling Unmanaged Functions
C# also has the concept of function pointers and can call unmanaged functions through P/Invoke. You can use methods in the Marshal class to convert a pointer into a typed function delegate.
// Declare the function type
delegate void TestDelegate(int a);
// Get the delegate
var func = Marshal.GetDelegateForFunctionPointer<TestDelegate>(ptr);
After that, func can be called directly. I have to say, C# really makes this part convenient.
You can also directly declare a delegate* function pointer with the following syntax.
unsafe delegate* unmanaged<int, int> TestPtr = (delegate* unmanaged<int, int>)(void*)0x00000000;
Very hacky syntax. The last generic parameter is the return type; passing void means no return value.
Importing Functions
C# provides the LibraryImport and DllImport attributes to help import symbol functions. The symbol name matches the actual symbol name (it may be the original extern "C" symbol name, or a C++ mangled name). LibraryImport is newer and recommended; I won't go into the implementation details here.
Calling Conventions
If, like me, your development scope is limited to x64, then congratulations—you can escape calling convention troubles. But if you also need x86 support, don't worry, C# also supports different calling conventions.
On delegates, you can use the UnmanagedFunctionPointer attribute to specify a delegate's calling convention type.
[UnmanagedFunctionPointer(CallingConvention.FastCall)]
delegate void TestDelegate();
For function pointers, you can also use the following syntax.
unsafe delegate* unmanaged[Fastcall]<int, int> TestPtr = (delegate* unmanaged[Fastcall]<int, int>)(void*)0x00000000;
Marshalling
For some special value types, C# provides custom Marshal schemes so users can specify how parameters should be passed.
One thing to call out here is the C# bool type. The default Marshal behavior for C# bool is to pass it as 4 bytes. That doesn't match the design of most bools today, so developers have to be careful when handling it. Alternatives are replacing all bools with byte, or using the MarshalAs attribute to specify. If you don't handle it properly, hard-to-track memory errors can occur (especially when unmanaged code calls managed functions).
The Structs section also mentioned that string is UTF-16 underneath. If you try to use a fixed statement to convert a string to char* (which is completely allowed in C#) and then directly cast it to byte* to pass to a C function that accepts char*, it will cause an error. The correct approach is to use Encoding.UTF8.GetBytes for conversion.
ABI
Although C#'s support for Linux is mostly complete, there are still many pitfalls to watch out for. A typical example is the 16-byte struct register expansion for Linux parameters. When a struct of 16 bytes or less is passed by value, SystemV ABI often expands it into two registers and passes them directly, while C# doesn't do this by default. You need to always pay attention and make sure the registers match, otherwise hard-to-track memory errors will occur.
Virtual Functions
When dealing with C++ virtual functions, note that the first parameter is the this pointer.
Calling Managed Functions from Unmanaged Code
C# also allows you to create unmanaged function pointers and pass them to unmanaged code to call. Most of the function concepts have already been covered above, so here I'll introduce how to create function pointers.
The first way is to set the UnmanagedCallerOnly attribute on a static function and take the function's pointer directly with the & operator (a type conversion is needed afterward).
The second way is to use the Marshal function:
nint ptr = Marshal.GetFunctionPointerForDelegate(Func);
Note that these managed functions must be kept from being GC'd. Otherwise C# will throw an exception that causes a crash.
C# has GCHandle, which lets you manage the lifecycle of a callback completely.
Hook
For plugin scenarios, a common need is inline hooking. Thanks to C# unmanaged function pointers, you can pair them with inline hook libraries (such as safetyhook) without much friction. You can directly use a function pointer as a hook target, install it on an unmanaged function, and implement an inline hook. Note that the managed function's parameter signature must exactly match the unmanaged function's, otherwise it will cause register mismatches and eventually memory errors. A typical example is forgetting to add a return value, which causes a garbage return value and makes subsequent function calls fail. This part is also related to the small struct expansion mentioned earlier.
SafeHandle
C# provides the SafeHandle class to help you manage the lifecycle of unmanaged objects. It implements handle lifecycle management through IDisposable and reference counting. You can inherit from SafeHandle to implement your own SafeHandle. SafeHandle can be the return value of a function imported by LibraryImport or DllImport; C# handles the type automatically. Using SafeHandle to manage pointer lifetime is best practice.
Besides letting your struct inherit SafeHandle, you can also implement SafeHandle compositionally (set a custom SafeHandle class as a field of the wrapper). This pattern is often used for Wrapper classes around native objects. When Dispose is called, calling Dispose on the SafeHandle field as well achieves lifecycle management. The benefit of this pattern is that SafeHandle-related methods won't be exposed to the external API.
Memory Allocators
C# has several memory allocators: CoTaskMemAlloc/Free, Alloc/FreeHGlobal, and the NativeMemory class. To tell the differences apart, I recommend referring directly to the CoreCLR source code and the C# underlying implementation (data from the publication date of this article).
CoTask
Windows
Import functions such as CoTaskMemAlloc from combaseapi.h:
CoTaskMemAlloc(
_In_ SIZE_T cb
);
Linux (minipal)
#ifndef HOST_WINDOWS
inline void* CoTaskMemAlloc(size_t cb)
{
return malloc(cb);
}
inline void CoTaskMemFree(void* pv)
{
free(pv);
}
#endif
HGlobal
Windows (Kernel32)
public static unsafe IntPtr AllocHGlobal(nint cb)
{
void* pNewMem = Interop.Kernel32.LocalAlloc((nuint)cb);
if (pNewMem is null)
{
throw new OutOfMemoryException();
}
return (nint)pNewMem;
}
Linux
public static unsafe IntPtr AllocHGlobal(nint cb)
{
return (nint)NativeMemory.Alloc((nuint)cb);
}
NativeMemory
Windows
public static void* Alloc(nuint byteCount)
{
// The Windows implementation handles size == 0 as we expect
void* result = Interop.Ucrtbase.malloc(byteCount);
if (result == null)
{
ThrowHelper.ThrowOutOfMemoryException();
}
return result;
}
Linux
public static void* Alloc(nuint byteCount)
{
// The C standard does not define what happens when size == 0, we want an "empty" allocation
void* result = Interop.Sys.Malloc((byteCount != 0) ? byteCount : 1);
if (result == null)
{
ThrowHelper.ThrowOutOfMemoryException();
}
return result;
}
The differences among the three aren't obvious, and on Linux they all use malloc/free. As a recommendation, for now use NativeMemory for everything.
Host Process Allocator
Sometimes the plugin's host process uses its own allocator (such as mimalloc) and redirects all ucrt allocation functions and malloc/free allocation functions. In these cases, it's recommended to dynamically link your own native code to the same allocation functions as the host and use them in C#, to ensure memory consistency.
Virtual Function Tables
By combining structs and unmanaged functions, you can simulate C++ virtual function tables in C#. Set the field at offset +0x0 of the struct to a virtual table struct pointer, then define a series of unmanaged function pointers in the vtable struct, and you can achieve a similar effect.
Example:
[StructLayout(LayoutKind.Sequential)]
public unsafe struct VTable
{
public delegate* unmanaged<nint, void> Destructor;
public delegate* unmanaged<nint, int> GetValue;
}
[StructLayout(LayoutKind.Sequential)]
public struct CppObject
{
public VTable* VTablePtr;
// ...
}
Crash Analysis
C# natively provides .pdb files as symbols, which can be loaded directly in Windbg to view the callstack. If a managed call causes a memory crash, the C# caller will also appear on the callstack. This makes debugging much easier.
BenchmarkDotnet has disassembly support. You can use this framework to observe the assembly code generated by C#; I won't go into details here.
On Linux, LLDB also has decent .NET debugging support. You can install the corresponding plugin to analyze the managed heap and callstack.
In addition, .NET also provides a series of tools for dump analysis and runtime analysis (such as dotnet-monitor, dotnet-sos). These tools can also be used to analyze memory usage, GC, deadlocks, and other issues.
The CoreCLR Profiling API is also a highlight of .NET. It provides a series of detailed interfaces that let you fully monitor and analyze events on the CoreCLR side. In practice, combined with breakpad, it can implement user-side crash tracking.
To be continued...
