This commit is contained in:
Maurice
2023-10-17 19:00:03 +02:00
commit 828e08c6ce
8 changed files with 564 additions and 0 deletions

43
FfiChannels/Ffi.cs Normal file
View File

@@ -0,0 +1,43 @@
using System.Runtime.InteropServices;
namespace FfiChannels
{
[StructLayout(LayoutKind.Sequential)]
public struct ByteArray
{
public IntPtr data;
public int length;
public byte[] ToByteArray() {
var array = new byte[length];
Marshal.Copy(data, array, 0, length);
return array;
}
}
public delegate void Callback(ByteArray byteArray);
public static class Bindings {
[DllImport("ffi_channels")]
public static extern void send(byte[] data, int length);
[DllImport("ffi_channels")]
public static extern ByteArray receive();
[DllImport("ffi_channels")]
public static extern void register_callback(Callback cb);
[DllImport("ffi_channels")]
public static extern void start_listening();
public static Task<byte[]> ReceiveAsync() {
return Task.Run(() => {
Console.WriteLine("Receiving..");
var ptr = receive(); //blocking call
Console.WriteLine("Received!");
return ptr.ToByteArray();
});
}
}
}

View File

@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<NativeOutputPath>../target/debug</NativeOutputPath>
<LibraryName>ffi_channels</LibraryName>
</PropertyGroup>
<ItemGroup>
<None Condition="$([MSBuild]::IsOsPlatform('MacOS'))" Include="$(NativeOutputPath)/lib$(LibraryName).dylib" CopyToOutputDirectory="PreserveNewest" />
<None Condition="$([MSBuild]::IsOsPlatform('Linux'))" Include="$(NativeOutputPath)/lib$(LibraryName).so" CopyToOutputDirectory="PreserveNewest" />
<None Condition="$([MSBuild]::IsOsPlatform('Windows'))" Include="$(NativeOutputPath)/$(LibraryName).dll" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>

25
FfiChannels/Program.cs Normal file
View File

@@ -0,0 +1,25 @@
using FfiChannels;
Bindings.register_callback((bytes) => {
var data = bytes.ToByteArray();
Console.WriteLine($"Callback called, bytes: {string.Join(',',data)}");
});
Bindings.start_listening();
Console.WriteLine("Press key to send");
Console.ReadKey(true);
Bindings.send(new byte[]{ 1,2,3,4,5,6,7,8,9,10 }, 10);
Console.WriteLine("Press key to exit");
Console.ReadKey(true);
// var receiving = Bindings.ReceiveAsync();
// Console.WriteLine("Press key to send");
// Console.ReadKey(true);
// Console.WriteLine("Hello world, sending data to Rust:");
// Bindings.send(new byte[]{ 1,2,3,4,5,6,7,8,9,10 }, 10);
// Console.WriteLine("Press a key to receive");
// Console.ReadKey(true);
// var data = await receiving;
// Console.WriteLine($"Received: {string.Join(',',data)}");