C# and Infrastructure. Code is everything.

This post was originally published on Red Hat Developers, the community to learn, code, and share faster. To read the original post, click here.

P/Invoke(Platform Invocation Service) is one of the features of CLI (Common Language Interface) on .NET Framework. P/Invoke enables managed code to call a native function in DLL (Dynamic Link Library). It’s a powerful tool for .NET Framework to execute existing C-style functions easily. .NET Core also has a P/Invoke feature and it means we can call a native function in .so file (Linux) and . file (Max OSX). I will show you the short example P/Invoke in .NET Core on Red Hat Enterprise Linux (RHEL).

Here is the simple P/Invoke sample using read function in libc. It is the same way as .NET Framework on Windows to import native function.

[dllimport] is the attribute to import a native function. We can declare method name as a native function name, and declare method name as you like with specifying native function name in EntryPoint attribute value as below.

Next, I’d like to execute GUI sample written in .NET Core on RHEL. .NET Core doesn’t have GUI Framework at this point. However, we can call GUI library such as gtk+ from managed code in .NET Core. At first, install the package.

$ sudo yum install gtk3-devel

Now we can call functions in gtk+ from C# code. Here is the whole code to open dialog from C#.

P/Invoke was a technology only for Windows platform, but now it enables many platforms to call native function easily from managed code. Of course, we shouldn’t forget Mono, which enabled P/Invoke on Linux.