RingDotNetfor Ring

Native DLLs

Windows has thousands of functions in DLLs such as kernel32 and user32, and many programs come with a DLL of their own. .NET calls them with P/Invoke. Ring does not declare them, but a small C# library does, and then Ring uses the functions like any other class. This lesson shows it with five functions of the Windows API.

What you will learn#

The problem#

The bridge calls the members that .NET already has: a method of a class, a property, a constructor. A function of a native DLL is not a .NET member until C# declares it. The declaration is called P/Invoke (platform invoke): [DllImport("kernel32.dll")] before a method with the same name and the same parameters as the native function.

So the plan is the one of the tutorial A library written in C#: a few lines of C# declare the functions and give them public methods, the generator wraps that library, and Ring calls the methods.

Note

This lesson uses the DLLs of Windows, so it runs on Windows only (the program says so on another system). Other systems have their own libraries (libc, libm) and the same idea works with their names.

The steps#

  1. Declare the functions in C# with [DllImport] and give them public methods.
  2. Build the library: dotnet build Native -c Release -o Native/bin.
  3. Wrap and load it: wrapassembly.ring, dnLoad, dnImportFrom.
  4. Use it: new Win32() and the methods.

The C# library#

It is in samples/UsingDotNet/tutorials/Native:

samples/UsingDotNet/tutorials/Native/Win32.cs
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Tutorial.Native
{
    // Ring cannot declare a function of a native DLL, because the bridge calls members that .NET already knows.
    // C# can: [DllImport] says in which DLL the function is, and the public methods below give the functions to Ring.
    public static class Win32
    {
        [DllImport("kernel32.dll")]
        private static extern int MulDiv(int number, int numerator, int denominator);

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        private static extern IntPtr CharUpperW(IntPtr text);

        [DllImport("user32.dll")]
        private static extern int GetSystemMetrics(int index);

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern uint GetEnvironmentVariableW(string name, StringBuilder buffer, uint size);

        [StructLayout(LayoutKind.Sequential)]
        private struct MemoryStatus
        {
            public uint Length;
            public uint MemoryLoad;
            public ulong TotalPhysical;
            public ulong AvailablePhysical;
            public ulong TotalPageFile;
            public ulong AvailablePageFile;
            public ulong TotalVirtual;
            public ulong AvailableVirtual;
            public ulong AvailableExtendedVirtual;
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GlobalMemoryStatusEx(ref MemoryStatus status);

        // numbers in, a number out: (number * numerator) / denominator, rounded
        public static int Scale(int number, int numerator, int denominator)
        {
            return MulDiv(number, numerator, denominator);
        }

        // a text in, a text out: the function changes the text itself, so it gets a copy in native memory
        public static string UpperCase(string text)
        {
            IntPtr copy = Marshal.StringToHGlobalUni(text);
            try
            {
                CharUpperW(copy);
                return Marshal.PtrToStringUni(copy);
            }
            finally
            {
                Marshal.FreeHGlobal(copy);
            }
        }

        // 0 is the width of the screen in pixels, 1 is the height
        public static int ScreenSize(int which)
        {
            return GetSystemMetrics(which);
        }

        // a function that fills a buffer: the text of an environment variable, or "" when there is none
        public static string Variable(string name)
        {
            StringBuilder buffer = new StringBuilder(32768);
            uint length = GetEnvironmentVariableW(name, buffer, (uint)buffer.Capacity);
            return length == 0 ? "" : buffer.ToString();
        }

        // a function that fills a structure: the physical memory of the computer in megabytes
        public static long MemoryMegabytes()
        {
            MemoryStatus status = new MemoryStatus();
            status.Length = (uint)Marshal.SizeOf(typeof(MemoryStatus));
            if (!GlobalMemoryStatusEx(ref status))
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            return (long)(status.TotalPhysical / (1024 * 1024));
        }
    }
}
samples/UsingDotNet/tutorials/Native/Native.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <AssemblyName>Native</AssemblyName>
    <DebugType>none</DebugType>
  </PropertyGroup>
</Project>

The Ring program#

samples/UsingDotNet/tutorials/ch13_native.ring
# a function of a native DLL (Windows API) - a small C# library with [DllImport] gives it to Ring, and Ring uses it like any other class
#   (the library is in the folder Native: Win32.cs and Native.csproj)
load "dotnet.ring"

if not iswindows()
	? "The functions of this lesson are in the DLLs of Windows (kernel32 and user32), so it runs on Windows only."
	bye
ok

cHere = currentdir()
cDll = cHere + "/Native/bin/Native.dll"
cClasses = cHere + "/Native/classes"

# STEP 1. Build the C# library (the .NET SDK is needed for this step only)
if not fexists(cDll)
	? "building the library..."
	system("dotnet build Native -c Release -o Native/bin -nologo -v q > nul")
ok

# STEP 2. Make Ring classes for it (tools/dotnettools/wrapassembly.ring)
chdir("../../../tools/dotnettools")
system(exefilename() + " wrapassembly.ring " + cDll + " " + cClasses + " > nul")
chdir(cHere)

# STEP 3. Load the assembly and the classes
dnLoad(cDll)
dnImportFrom(cClasses + "/","Tutorial.Native")

func main

	# STEP 4. Use the class. Win32 is a static class, and a static method is called on an object, as with Math.
	oWin = new Win32()

	# numbers in, a number out: kernel32.MulDiv(10, 3, 4) is 10 * 3 / 4 rounded
	? "Scale(10,3,4)             : " + oWin.Scale(10,3,4)

	# a text that the function changes in place
	? "UpperCase('ring')         : " + oWin.UpperCase("ring")

	# a function that fills a buffer with a text
	cPath = oWin.Variable("PATH")
	? "the PATH is not empty     : " + (len(cPath) > 0)
	? "a missing variable is ''  : [" + oWin.Variable("NO_SUCH_VARIABLE_FOR_THE_TUTORIAL") + "]"

	# a function that fills a structure
	? "the computer has more than 1 GB of memory : " + (oWin.MemoryMegabytes() > 1024)

	# a number from the system (a yes/no is 1 or 0 in Ring)
	? "the screen is wider than 0 : " + (oWin.ScreenSize(0) > 0)
Output
Scale(10,3,4)             : 8
UpperCase('ring')         : RING
the PATH is not empty     : 1
a missing variable is ''  : []
the computer has more than 1 GB of memory : 1
the screen is wider than 0 : 1

How it works#

Declaring a function#

The documentation of a Windows function shows its C signature, for example int MulDiv(int nNumber, int nNumerator, int nDenominator) in kernel32.dll. The C# declaration repeats it with static extern. The names of the parameters do not matter, the order and the types do. Here the Windows types become C# types like this:

In C (Windows)In C#In Ring
int, DWORD, longint, uint, inta number
ULONGLONG, QWORDulonga number
BOOLbool with [return: MarshalAs(UnmanagedType.Bool)]1 or 0
LPCWSTR (a text that is only read)string, with CharSet = CharSet.Unicodea text
LPWSTR (a buffer that the function fills)StringBuilder with a capacitya text
a pointer to a structurea struct with [StructLayout], passed with ref–
HANDLE, HWND, any pointerIntPtrnot given to Ring (keep it inside C#)

Windows has two versions of a function that takes a text: GetEnvironmentVariableA for old 8-bit text and GetEnvironmentVariableW for Unicode (wide). Name the W version and use CharSet.Unicode.

What Ring sees#

Ring never sees a pointer or a structure here: the public methods of Win32 take and return numbers and texts, and everything else stays in C#. That is the rule to follow for your own library, because a method with simple types is the easiest to wrap and to call. (The bridge can pass an address, a buffer or a Span<T> to a method that takes one, see Advanced .NET types; a small C# layer is still the simplest way to use a native library.)

When the call fails#

A native function reports an error with a return value: 0 or false. The details are kept by Windows, and SetLastError = true in [DllImport] tells .NET to remember them. Marshal.GetLastWin32Error() reads the number, and new Win32Exception(number) makes an exception with the text of Windows for it. MemoryMegabytes does this. Ring then catches it like every other .NET error (the tutorial When things go wrong).

Some rules#

What you learned#

Exercises#

  1. Declare GetTickCount64 in kernel32.dll (it returns a ulong), give it a public method UptimeSeconds() and print how long the computer has been running.
  2. Use GetSystemMetrics(1) to print the height of the screen, and GetSystemMetrics(80) for the number of monitors.
  3. Declare CharLowerW the same way as CharUpperW, and write SwapCase in C# that uses both on one letter at a time.
  4. Call MulDiv with 0 as the denominator. What does it return? Look the answer up in the documentation of the function.

Next#

A project: from CSV to Excel

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.