In this final article of our C# 9 series, we’ll look at advanced features related to native interop and performance in C# 9.
If you missed any of the previous articles in this series, here's where you can catch up:
- Part 1: C# 9 top-level programs and target-typed expressions
- Part 2: C# 9 pattern matching
- Part 3: C# 9 new features for methods and functions
- Part 4: C# 9 init accessors and records
Native-sized integers
C# 9 introduces language support for native-sized integer types, both signed and unsigned. The existing C# int
and long
types, which map to the underlying System.Int32
and System.Int64
types, have a fixed size of 32 bits and 64 bits, respectively. The new nint
and nuint
types, which map to the existing System.IntPtr
and System.UIntPtr
types, have a size that corresponds to the native machine size. That means they are 32 bit on a 32-bit machine and 64 bit on a 64-bit machine.
C# supports direct arithmetic on nint
and nuint
:
// IntPtr aren't directly usable for arithmetic. IntPtr a = (IntPtr)5; IntPtr b = (IntPtr)6; IntPtr c = new IntPtr((long)a + (long)b); // nint/nuint can be used for arithmetic. nint i = 5; nint j = 6; nint k = i + j; // cast required: int-size may be smaller. int y = (int)i;
Native integers can be marked const
, but only when the compiler knows that the result won’t overflow on any architecture:
const nint n = int.MaxValue; // error CS0133: The expression being assigned to 'm' must be constant. const nint m = unchecked(n + 1);
Native libraries often use machine-sized native integers in their APIs, and the new nint
/nuint
facilitate using such APIs from .NET:
public unsafe int write(int fd, Span buffer) { fixed(byte* buf = buffer) { return (int)write(fd, buf, (nuint)buffer.Length); } // ssize_t write(int fd, const void *buf, size_t count); // ssize_t, and size_t are signed/unsigned native-size integer types. [DllImport("libc", SetLastError = true)] static extern nint write(int fd, void* buf, nuint count); }
Suppressing localsinit
The localsinit
feature can improve performance. To understand it, have a look at the following method:
void ReadData() { Span buffer = stackalloc byte[256]; int bytesRead = Read(buffer); buffer = buffer.Slice(0, bytesRead); ProcessData(buffer); }
Each time this method is called, the runtime ensures that the allocated buffer is zeroed so that the method won't read uninitialized data from the stack. The C# compiler emits the .locals init
directive in the method for this to happen.
When performance is critical, it may be desirable to omit this zeroing. C# 9 supports that performance measure through the new SkipLocalsInit
attribute. This attribute can be applied at the method level, the class level, or even for the entire module:
// For the entire project. [module: System.Runtime.CompilerServices.SkipLocalsInit] // or, for a specific method. [SkipLocalsInit] void ReadData() { // ...
If you add this attribute, be careful to initialize variables that are used as out
parameters or whose addresses you pass to another function. Those variables will no longer be zeroed by the compiler:
[SkipLocalsInit] unsafe void Foo() { int i; // i is not cleared. Bar(&i); }
Module initializers
C# supports static
type constructors, which get called only once when the type is first used. C# 9 makes it possible to add a constructor at the assembly level (more specific: module level). This module initializer runs one time when the module is first used.
Compared to static constructors, a module initializer is more efficient because the runtime doesn’t have to track whether the constructor has been called for each type. Additionally, a module initializer avoids ordering issues that may exist between multiple static constructors.
A method can be marked as a module initializer by adding the ModuleInitializer attribute. The method must be public
or internal
, have a void
return type, and must not accept parameters:
static void Main(string[] args) { Console.WriteLine("Hello from Main."); } [ModuleInitializer] static internal void MyInitializer() { Console.WriteLine("Hello from initializer!"); }
Multiple methods can have the ModuleInitializer
attribute. The compiler generates a module initializer that calls all of them.
Function pointers
C# has always supported passing methods using delegates. Delegates are reference types and refer to one or more methods that can be invoked through the delegate:
Action<string> myDelegate = s => Console.WriteLine($"Hello 1 {s}"); myDelegate += s => Console.WriteLine($"Hello 2 {s}"); myDelegate("world!");
C# 9 goes a level deeper and allows you to use function pointers directly in C#. Function pointers contain just the address of the function. They may only be used in unsafe blocks.
Function pointers can refer to managed static methods or native functions. For native functions, you can further specify the calling convention if the default is not appropriate. This tells the JIT how arguments need to be passed to the function.
Function pointers are declared using delegate*
. The next example declares three function pointers:
var pFun1 = (delegate* unmanaged<int, void>)NativeLibrary.GetExport(libHandle, "fun1"); var pFun2 = (delegate* unmanaged[Stdcall]<int, void>)NativeLibrary.GetExport(libHandle, "fun2"); delegate*<int, void> pManagedFunction = &ManagedFunction;
The first two pointers are unmanaged
and initialized using the NativeLibrary class. The type parameters are the same as for the Func
delegate: first the argument types, and finally the return type. The pointers declared here accept an int
and have no return type (void
).
The second function pointer specifies the Stdcall calling convention to change from the platform default.
The third function pointer is a managed function pointer. It is assigned using the address-of operator on a static method.
Function calls can be made using the expected call syntax:
pManagedFunction(10);
A special case is passing the address of a managed method to a native library. For this, we need to add the UnmanagedCallersOnly attribute to the method. This tells the runtime the method will be called from native code. Such methods must not be called from managed code and can have only blittable arguments:
[UnmanagedCallersOnly] static void Log(IntPtr ptr) { Console.Write(Marshal.PtrToStringAnsi(ptr)); } static unsafe void Main(string[] args) { delegate* unmanaged<IntPtr, void> pLog = &Log; nativelib_set_log_function(pLog); ... }
Conclusion
In this article, we looked at the new nint
and nuint
native-sized integer types and how they facilitate interop. We learned how the SkipLocalsInit
attribute can avoid the cost of zeroing stack locals. We covered how module initializers allow you to run one or more methods when an assembly or module is first used. And finally, we looked at function pointers and how they can be used with managed and unmanaged functions.
C# 9 can be used with the .NET 5 SDK, which is available on Red Hat Enterprise Linux, Red Hat OpenShift, Fedora, Windows, macOS, and other Linux distributions. For more information on Red Hat's support for .NET, see the Red Hat Developer .NET topic page.
Last updated: February 5, 2024