csharp_rpc 0.0.1 csharp_rpc: ^0.0.1 copied to clipboard
Execute C# code from Dart (Flutter) application.
Flutter Csharp RPC #
With this package we can execute C# code from Dart (Flutter) application via JSON-RPC protocol.
In run-time, we will create a C# child process and communicate with it via JSON-RPC protocol on the standard in/out (stdin/stdout) stream.
The JSON-RPC protocol let us invoke C# methods on the child process.
For example, we have the C# method:
public DateTime GetCurrentDateTime()
{
return DateTime.Now;
}
And we call it from Dart code with the invoke
method:
String currentDateTime = await csharpRpc.invoke(method: "GetCurrentDateTime");
We can also invoke method with array of parameters:
var sum = await csharpRpc.invoke<int>(method: "SumNumbers", params: [2, 3]);
And even send a typed request parameter:
var filesResult = await csharpRpc.invoke(
method: "GetFilesInFolder",
param: GetFilesInFolderRequest(folderPath: Directory.current.path)
);
var files = FilesInFolderResponse.fromJson(filesResult);
here we sending instance of request type GetFilesInFolderRequest
,
then we convert the result to a response type FilesInFolderResponse
with the fromJson
method, so we can have fully typed communication experience 🎉
📋 Dart/Flutter Setup #
In your pubspec.yaml
, add the csharp_rpc
package as a new dependency with
the following command:
PS c:\src\flutter_project> flutter pub add csharp_rpc
In your program code, create and use the CsharpRpc
class to invoke methods:
import 'package:csharp_rpc/csharp_rpc.dart';
// create instance of CsharpRpc
var pathToCsharpExecutableFile = "<path_to_your_csharp_app>/CsharpApp.exe";
CsharpRpc csharpRpc = await CsharpRpc(pathToCsharpExecutableFile).start();
// invoke the C# method 'GetCurrentDateTime'
var currentDateTime = await csharpRpc.invoke(method: "GetCurrentDateTime");
📋 C# Setup #
In your C# project, add the FlutterCsharpRpc
Nuget package as a new dependency with
the following command:
PS c:\src\flutter_project> dotnet add package FlutterCsharpRpc
In your program code, start the JSON-RPC server by calling the StartAsync
method:
using FlutterCsharpRpc;
static async Task Main(string[] args)
{
// your program setup (DI, service, etc) here...
// start the JSON-RPC server
await CsharpRpcServer.StartAsync(new Server());
}
public class Server
{
public DateTime GetCurrentDateTime()
{
return DateTime.Now;
}
}
⚡ Demo #
See the full demo of Flutter and C# app that communicate between them.
Tags: Csharp
C#
RPC
flutter csharp
flutter c#
csharp ffi
csharp json-rpc
FlutterCsharpRpc
StreamJsonRpc