Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Quick links: redhat.com, Customer Portal, Red Hat's developer site, Red Hat's partner site.

  • You are here

    Red Hat

    Learn about our open source products, services, and company.

  • You are here

    Red Hat Customer Portal

    Get product support and knowledge from the open source experts.

  • You are here

    Red Hat Developer

    Read developer tutorials and download Red Hat software for cloud application development.

  • You are here

    Red Hat Partner Connect

    Get training, subscriptions, certifications, and more for partners to build, sell, and support customer solutions.

Products & tools

  • Ansible.com

    Learn about and try our IT automation product.
  • Red Hat Ecosystem Catalog

    Find hardware, software, and cloud providers―and download container images―certified to perform with Red Hat technologies.

Try, buy, & sell

  • Red Hat Hybrid Cloud Console

    Access technical how-tos, tutorials, and learning paths focused on Red Hat’s hybrid cloud managed services.
  • Red Hat Store

    Buy select Red Hat products and services online.
  • Red Hat Marketplace

    Try, buy, sell, and manage certified enterprise software for container-based environments.

Events

  • Red Hat Summit and AnsibleFest

    Register for and learn about our annual open source IT industry event.

Using .NET PInvoke for Linux system functions

March 25, 2019
Tom Deseyn
Related topics:
.NETC, C#, C++Linux
Related products:
Red Hat Enterprise Linux

Share:

Share on twitter Share on facebook Share on linkedin Share with email
  • PInvoking Linux
  • Mono.Posix.NETStandard
  • Tmds.LibC
  • Conclusion

If you've developed Windows applications with .NET, you may have found yourself in a situation where the framework did not provide the APIs you needed. When that happens, you first need to identify the system APIs and then make them available using PInvoke. A website like pinvoke.net provides copy-and-pasteable code snippets for many Win32 API functions.

.NET Platform Invoke (PInvoke) makes it easy to consume native libraries. In this article, we'll take a look at using PInvoke for Linux system functions.

PInvoking Linux

PInvoking Linux

In case you are not familiar with PInvoke, let's look at a simple example:

[DllImport("mylibrary")]
public static extern int foo();

This makes available the function foo from the native library mylibrary. This function accepts no arguments and returns an int. .NET takes care of marshaling the argument types. It is possible to use managed types (like strings) in these signatures, which will be automagically marshaled.

PInvoke works at the application binary interface (ABI) level: It respects the binary calling conventions of the platform on which it is running.

Linux is a UNIX flavor operating system. It provides many of the APIs prescribed by POSIX and SUS; however, these APIs are defined using the C programming language. They are not APIs at the binary level (ABIs).

For example, the standards describe that there should be positive values for indicating certain types of errors. These values are named (for example, EAGAIN), but their values are not defined. This means different platforms can (and will) have different values for these names. This makes it impossible to add a const int to a C# file that has the correct value for all platforms.

Another example is struct, which is used in the API to define a number of fields; however, the order is not fixed, and platforms are allowed to add extra fields. So again, we can't describe a struct in C# that matches the native struct on all platforms.

The generic way to solve this is to introduce a native shim library. This library provides its own set of functions, constants, and structs that are platform-independent with a fixed ABI. This API gets PInvoked by .NET. Within the library, this API calls the native functions.

If you want to PInvoke the system C library without using a shim, you can use libc as the library name. The .NET Core runtime maps this to the system C library. For example, we can expose the kill function as follows:

[DllImport("libc", SetLastError = true))]
public static extern int kill(int pid, int sig);

SetLastError means the function uses errno to indicate what went wrong. Marshal.GetLastWin32Error can be used to retrieve errno.

Mono.Posix.NETStandard

Mono.Posix.NETStandard

The Mono.Posix.NETStandard package provides system functions. It uses native shims to work across a number of platforms. If we download the package from nuget.org, we can take a look inside:

$ unzip -l mono.posix.netstandard.1.0.0.nupkg
Archive:  mono.posix.netstandard.1.0.0.nupkg
  Length  	Date	Time	Name
---------  ---------- -----   ----
  	516  02-28-2018 15:18   _rels/.rels
  	814  02-28-2018 15:18   Mono.Posix.NETStandard.nuspec
	13376  02-28-2018 15:18   lib/net40/Mono.Posix.NETStandard.dll
	13376  02-28-2018 15:18   ref/net40/Mono.Posix.NETStandard.dll
   189504  02-28-2018 15:18   ref/netstandard2.0/Mono.Posix.NETStandard.dll
   189504  02-28-2018 15:18   runtimes/linux-arm/lib/netstandard2.0/Mono.Posix.NETStandard.dll
   183240  02-28-2018 15:18   runtimes/linux-arm/native/libMonoPosixHelper.so
   189504  02-28-2018 15:18   runtimes/linux-arm64/lib/netstandard2.0/Mono.Posix.NETStandard.dll
   246736  02-28-2018 15:18   runtimes/linux-arm64/native/libMonoPosixHelper.so
   189504  02-28-2018 15:18   runtimes/linux-armel/lib/netstandard2.0/Mono.Posix.NETStandard.dll
   236480  02-28-2018 15:18   runtimes/linux-armel/native/libMonoPosixHelper.so
   189504  02-28-2018 15:18   runtimes/linux-x64/lib/netstandard2.0/Mono.Posix.NETStandard.dll
   920882  02-28-2018 15:18   runtimes/linux-x64/native/libMonoPosixHelper.so
   189504  02-28-2018 15:18   runtimes/linux-x86/lib/netstandard2.0/Mono.Posix.NETStandard.dll
   766620  02-28-2018 15:18   runtimes/linux-x86/native/libMonoPosixHelper.so
   189504  02-28-2018 15:18   runtimes/osx/lib/netstandard2.0/Mono.Posix.NETStandard.dll
   535888  02-28-2018 15:18   runtimes/osx/native/libMonoPosixHelper.dylib
   189504  02-28-2018 15:18   runtimes/win-x64/lib/netstandard2.0/Mono.Posix.NETStandard.dll
  1495800  02-28-2018 15:18   runtimes/win-x64/native/libMonoPosixHelper.dll
	87600  02-28-2018 15:18   runtimes/win-x64/native/MonoPosixHelper.dll
   189504  02-28-2018 15:18   runtimes/win-x86/lib/netstandard2.0/Mono.Posix.NETStandard.dll
  1256296  02-28-2018 15:18   runtimes/win-x86/native/libMonoPosixHelper.dll
   400120  02-28-2018 15:18   runtimes/win-x86/native/MonoPosixHelper.dll
  	592  02-28-2018 15:18   [Content_Types].xml
  	692  02-28-2018 15:18   package/services/metadata/core-properties/4b5c471cadba4490965015071f90289f.psmdcp
 	9475  10-11-2018 20:23   .signature.p7s
---------                 	-------
  7874039                 	26 files

The libMonoPosixHelper.* files are the native shim libraries. The directories under runtimes are the supported platforms. There is Linux support for arm, arm64, armel, x64 and x86. The package also provides support for Windows and OS X. The Linux libraries are for flavors of Linux that are based on glibc (GNU C library), such as Fedora and Red Hat Enterprise Linux (RHEL). Some things won't work on flavors of Linux that are based on musl, such as Alpine. .NET Core applications using this package will pick the proper variant under the runtimes folder based on the platform on which they are running. This is based on the runtime identifier (RID) graph.

Tmds.LibC

Tmds.LibC

A while back, I blogged about a Linux-specific transport for Kestrel. This library uses Linux-specific APIs that are not provided by .NET Core and Mono.Posix.NETStandard. So far, the library has used a native shim to make those functions accessible. A compiled version for glibc x64 is in the NuGet package. This means the Transport doesn’t work on other architectures or with other C libraries.

As explained before, one way to solve this is to recompile the shim for different platforms. While that is easy to do in theory, in practice, there is quite a bit of work involved. On each platform, the native libraries need to be built. Then those libraries need to be collected in a single NuGet package. I wanted to try a different approach: a fully managed implementation.

The managed implementation captures the platform ABIs in managed code. For each platform, we build an assembly that matches that platform’s ABI. The differences between platforms are small, so we can share a lot of code between them.

A nice effect of capturing the platform ABIs is that our .NET API can be very close to the C API. We don’t need to introduce shim structs or shim constants.

For example, the setsockopt option for changing a socket option has this C API:

int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen);

The C# API looks like this:

public static int setsockopt(int socket, int level, int optname, void* optval, socklen_t optlen);

As you can see, the signatures are virtually the same.

Because these system functions may be useful for other developers, I’ve collected them in a separate library, named Tmds.LibC. You can find the source code on GitHub and packages are published to NuGet.org. The Kestrel Linux Transport has been updated to use this library. The Transport does not need to deal with platform specifics, and it now runs on arm32, arm64, and x64.

Conclusion

Conclusion

In this article, we looked at .NET PInvoke and how PInvoke differs on Linux compared to Windows. We then explored how Mono.Posix.NETStandard provides a set of POSIX functions on various platforms using native shims. Finally, we took a look at Tmds.LibC, which provides Linux system functions for a number architectures using a fully managed implementation.

Last updated: May 8, 2024

Recent Posts

  • LLM Compressor: Optimize LLMs for low-latency deployments

  • How to set up NVIDIA NIM on Red Hat OpenShift AI

  • Leveraging Ansible Event-Driven Automation for Automatic CPU Scaling in OpenShift Virtualization

  • Python packaging for RHEL 9 & 10 using pyproject RPM macros

  • Kafka Monthly Digest: April 2025

Red Hat Developers logo LinkedIn YouTube Twitter Facebook

Products

  • Red Hat Enterprise Linux
  • Red Hat OpenShift
  • Red Hat Ansible Automation Platform

Build

  • Developer Sandbox
  • Developer Tools
  • Interactive Tutorials
  • API Catalog

Quicklinks

  • Learning Resources
  • E-books
  • Cheat Sheets
  • Blog
  • Events
  • Newsletter

Communicate

  • About us
  • Contact sales
  • Find a partner
  • Report a website issue
  • Site Status Dashboard
  • Report a security problem

RED HAT DEVELOPER

Build here. Go anywhere.

We serve the builders. The problem solvers who create careers with code.

Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

Sign me up

Red Hat legal and privacy links

  • About Red Hat
  • Jobs
  • Events
  • Locations
  • Contact Red Hat
  • Red Hat Blog
  • Inclusion at Red Hat
  • Cool Stuff Store
  • Red Hat Summit

Red Hat legal and privacy links

  • Privacy statement
  • Terms of use
  • All policies and guidelines
  • Digital accessibility

Report a website issue