RustCSharpInterop/FfiChannels/Ffi.cs

43 lines
1.1 KiB
C#
Raw Normal View History

2023-10-17 17:00:03 +00:00
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();
});
}
}
}