P/Invoke

P/Invoke is the platform invoke mechanism: a C# program declares a method with [DllImport] and the runtime finds the native function, converts the arguments and calls it. The declarations of the operating system are in System.Runtime.InteropServices, and on Linux the library to call is libc.

A call into libc

The declarations live in a static class, and the program calls them as ordinary methods. The return types are the C types: int for a pid, nuint for a size, since a size is as wide as a pointer:

using System.Runtime.InteropServices; Console.WriteLine($"pid positive {Libc.getpid() > 0}"); Console.WriteLine($"strlen {Libc.strlen("hello")}"); Console.WriteLine($"toupper {(char)Libc.toupper('a')}"); Console.WriteLine($"getppid {Libc.getppid() > 0}"); static class Libc { [DllImport("libc", EntryPoint = "getpid")] public static extern int getpid(); [DllImport("libc", EntryPoint = "getppid")] public static extern int getppid(); [DllImport("libc", EntryPoint = "strlen")] public static extern nuint strlen(string text); [DllImport("libc", EntryPoint = "toupper")] public static extern int toupper(int c); }

dotnet run

pid positive True
strlen 5
toupper A
getppid True

Four C functions answered: the process id, the length of the string, the upper-case of a character, and the id of the parent process. The program prints booleans for the two ids because a pid changes on every run and the page should not pretend otherwise. The string was converted to a NUL-terminated byte array for the call, which is the default marshalling of a string parameter.

The declaration

The attribute and the signature are the whole contract, and the runtime checks it at the call, not at the build:

A library that is not there

A wrong library name fails when the method is called, with DllNotFoundException. The program catches it and prints the type:

using System.Runtime.InteropServices; try { Missing.hello(); } catch (DllNotFoundException) { Console.WriteLine("caught DllNotFoundException"); } Console.WriteLine("done"); static class Missing { [DllImport("nosuchlib")] public static extern int hello(); }

dotnet run

caught DllNotFoundException
done

The message of that exception lists every path the loader tried, one error line per candidate: the folder of the application, the folder of the runtime, and the same names with lib and .so. The catch is the place to turn that into a sentence a user can act on, such as "the native dependency is missing"; printing the whole message is for the log.

What portability costs

A P/Invoke declaration is a promise about a binary interface, and the promise is platform-specific. The same call needs a different library name on Windows (kernel32.dll instead of libc), a different struct layout when a field is a pointer, and a different calling convention on some platforms. A program that calls the operating system directly is a program that has one branch per system, and the branch belongs behind one small class so that the rest of the code does not know.

The alternative is a managed API when one exists: Environment.ProcessId is the pid without a native call, and File, Socket and Process cover most of what a program wants from the operating system. The next lesson takes the string and the struct of this one apart and measures how the runtime lays them out.

Exercises

  1. Call getuid and print whether the program runs as root.
  2. Declare strlen with an IntPtr parameter and pass a pointer you allocated.
  3. Call toupper with a character above 127 and see which byte it returns.
  4. Call a function of libm such as sqrt and read the declaration it needs.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which attribute declares a call into a native library?

    Answer

    DllImport

    DllImport names the library and the entry point of the function.

  2. Which library name resolves on this Linux system?

    Answer

    libc

    The measured calls into libc found getpid and strlen.

  3. What does this program print? using System.Runtime.InteropServices; Console.WriteLine(Libc.strlen("hello")); static class Libc { [DllImport("libc", EntryPoint = "strlen")] public static extern nuint strlen(string text); }

    Answer

    5

    strlen counts the five characters before the terminator.

  4. What does the CharSet argument of DllImport select?

    Answer

    How a string is marshalled to the native function

    Ansi and Unicode are the two forms, and the default is the platform one.

  5. What does this program print? using System.Runtime.InteropServices; Console.WriteLine((char)Libc.toupper('a')); static class Libc { [DllImport("libc", EntryPoint = "toupper")] public static extern int toupper(int c); }

    Answer

    A

    The function returns the upper-case code of the character.

  6. Which exception does a missing native library throw?

    Answer

    DllNotFoundException

    The measured call into nosuchlib threw DllNotFoundException.

  7. What does this program print? using System.Runtime.InteropServices; Console.WriteLine(Libc.getpid() > 0); static class Libc { [DllImport("libc", EntryPoint = "getpid")] public static extern int getpid(); }

    Answer

    True

    Every process has a positive id, which the measured boolean showed.

  8. Why is a P/Invoke declaration platform-specific?

    Answer

    The library name, the layout and the convention differ per system

    The same function lives in a differently named library on each system.

  9. Which managed type matches the C size_t of strlen?

    Answer

    nuint

    A size is as wide as a pointer, which nuint follows on each platform.

  10. When is a P/Invoke signature checked?

    Answer

    When the method is first called, by the runtime

    A wrong type compiles and fails at the call, which is the cost of the mechanism.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image