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#
- what P/Invoke is and why the bridge cannot do it alone,
- how to write
[DllImport]for a function, and how the types map, - numbers, texts, buffers and structures that go to a native function,
- how to give the functions to Ring in four steps,
- what to do when the call fails.
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.
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#
- Declare the functions in C# with
[DllImport]and give them public methods. - Build the library:
dotnet build Native -c Release -o Native/bin. - Wrap and load it:
wrapassembly.ring,dnLoad,dnImportFrom. - Use it:
new Win32()and the methods.
The C# library#
It is in samples/UsingDotNet/tutorials/Native:
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));
}
}
}<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<AssemblyName>Native</AssemblyName>
<DebugType>none</DebugType>
</PropertyGroup>
</Project>The Ring program#
# 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)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 : 1How 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, long | int, uint, int | a number |
ULONGLONG, QWORD | ulong | a number |
BOOL | bool with [return: MarshalAs(UnmanagedType.Bool)] | 1 or 0 |
LPCWSTR (a text that is only read) | string, with CharSet = CharSet.Unicode | a text |
LPWSTR (a buffer that the function fills) | StringBuilder with a capacity | a text |
| a pointer to a structure | a struct with [StructLayout], passed with ref | – |
HANDLE, HWND, any pointer | IntPtr | not 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.)
Scale(10,3,4)passes three numbers and gets one.UpperCaseshows a function that changes its text. Windows writes into the memory that it gets, so C# makes a copy in native memory (Marshal.StringToHGlobalUni), calls the function, reads the result back and frees the copy.Variableshows a buffer: the function writes the text into aStringBuilderthat has room, and returns the length (0 when the variable does not exist).MemoryMegabytesshows a structure: the function fills aMemoryStatus, and C# has set itsLengthfirst, which that function requires. The documentation of every function that takes a structure says which field must be set.
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#
- Check the signature twice. A wrong type does not give a message: a native function that gets the wrong kind of value may return nonsense, or stop the program. Copy the declaration from the documentation of the function (pinvoke.net has many).
- The bit size matters. A 64-bit program needs 64-bit DLLs, and
IntPtrhas the size of a pointer. UselongandIntPtrwhere the documentation says a handle or a size. - Free what you allocate. Memory from
Marshal.AllocHGlobalorStringToHGlobalUniis not managed: atry ... finallyfrees it, asUpperCasedoes. - Keep native things in C#. A callback that native code makes (for example
EnumWindows) must be a .NET delegate. Give it to the library, collect the answers there, and return a list or a text to Ring.
What you learned#
- a native function needs a C# declaration,
[DllImport], before Ring can use it, - the public methods of the library use numbers and texts, and C# does the marshalling,
- buffers and structures are filled inside C#,
SetLastErrorandWin32Exceptionbring the error of the system to Ring.
Exercises#
- Declare
GetTickCount64inkernel32.dll(it returns aulong), give it a public methodUptimeSeconds()and print how long the computer has been running. - Use
GetSystemMetrics(1)to print the height of the screen, andGetSystemMetrics(80)for the number of monitors. - Declare
CharLowerWthe same way asCharUpperW, and writeSwapCasein C# that uses both on one letter at a time. - Call
MulDivwith 0 as the denominator. What does it return? Look the answer up in the documentation of the function.