понедельник, 14 августа 2017 г.

.NET Core interop with C#: native and Go

Because I can.

.NET interop is a wonderful feature and I was happy to know that in .NET Core it is still powerful and convenient. While consuming native libraries is pretty starightforward at least on Windows but today we'll try some weird things on Mac OS (I'm pretty sure on Linux it will be the same).
Calling native functions is pretty simple. Let's start with creating a basic .NET Core application:



  mkdir interop   
  cd interop   
  dotnet new console  

Then open Program.cs in your favorite text editor and make the next changes:

 using System;  
 using System.Runtime.InteropServices;  
 namespace interop  
 {  
   class Program  
   {  
     [DllImport("libm")]  
     public static extern double sin(double angle);  
     static void Main(string[] args)  
     {  
       Console.WriteLine(sin(3.1415 / 2));  
     }  
   }  
 }  

Run this with

 dotnet run  

and you'll see the result close to 1.
Ok, let's try something more custom. What about some additions in the magical unmanage world? Create a file main.go in the "interop" folder with the following content:

 package main  
 import "C"  
 //export Add  
 func Add(a, b int) int {  
      return a+b  
 }  
 func main() {}  

Please pay attention to the "import C" and "//export Add" lines, they are crucial for the c-style shared libraries. Now let's build our lib into libgo.so file:

 go build -buildmode=c-shared -o libgo.so main.go  

Copy the output into /bin/Debug/{dotnet version} folder. Change Program.cs content to the following:

 using System;  
 using System.Runtime.InteropServices;  
 namespace interop  
 {  
   class Program  
   {  
     [DllImport("libm")]  
     public static extern double sin(double angle);  
     [DllImport("libgo.so")]  
     public static extern int Add(int a, int b);  
     static void Main(string[] args)  
     {        
       Console.WriteLine(sin(3.1415 / 2));      
       Console.WriteLine(Add(2,3));     
     }  
   }  
 }  

Wow, native addition! As you can see, this is pretty simple when working with value types. Next time we'll try to figure out how to process reference types.
The source code is available on my GitHub.

Комментариев нет:

Отправить комментарий