You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从一个.NET MAUI应用调用另一个MAUI应用中的函数?

.NET MAUI跨应用函数调用解决方案

两个独立的.NET MAUI应用属于不同进程,无法通过静态引用DLL直接调用函数,必须使用**进程间通信(IPC)**机制实现跨应用调用。以下分平台给出具体实现方案:

Windows平台实现

命名管道(Named Pipes)方案

这是Windows原生的本地IPC机制,轻量且易实现:

  • 被调用应用(服务端):
    在应用启动时初始化命名管道服务器,监听客户端请求并执行目标函数:
    // 可放在App.xaml.cs的OnStart方法或后台服务中
    using System.IO.Pipes;
    
    var pipeServer = new NamedPipeServerStream("MauiCrossAppPipe", PipeDirection.InOut, 1);
    pipeServer.WaitForConnection();
    
    using var reader = new StreamReader(pipeServer);
    using var writer = new StreamWriter(pipeServer);
    writer.AutoFlush = true;
    
    string request = reader.ReadLine();
    if (request == "InvokeTargetFunc")
    {
        // 执行你的目标函数
        string funcResult = YourNamespace.YourClass.TargetFunction();
        writer.WriteLine(funcResult);
    }
    
  • 发起调用的应用(客户端):
    按钮点击事件中连接管道,发送调用指令并接收结果:
    private async void CallFuncButton_Clicked(object sender, EventArgs e)
    {
        using var pipeClient = new NamedPipeClientStream(".", "MauiCrossAppPipe", PipeDirection.InOut);
        await pipeClient.ConnectAsync();
        
        using var reader = new StreamReader(pipeClient);
        using var writer = new StreamWriter(pipeClient);
        writer.AutoFlush = true;
    
        await writer.WriteLineAsync("InvokeTargetFunc");
        string result = await reader.ReadLineAsync();
        
        // 回到主线程更新UI
        await Dispatcher.DispatchAsync(() => ResultLabel.Text = result);
    }
    
  • 注意:需确保服务端应用先启动,可添加连接重试逻辑;管道名称需全局唯一,避免冲突。

macOS平台实现

XPC服务方案

XPC是macOS官方推荐的IPC机制,适合现代应用间通信:

  • 被调用应用(服务端):
    1. 在Xcode中为MAUI应用添加XPC服务目标,定义服务协议:
      // XPC服务的协议文件
      @objc protocol XPCServiceProtocol {
          func callTargetFunction(withReply reply: @escaping (String) -> Void)
      }
      
    2. 实现服务逻辑,桥接调用.NET MAUI中的目标函数:
      class XPCServiceImpl: NSObject, XPCServiceProtocol {
          func callTargetFunction(withReply reply: @escaping (String) -> Void) {
              // 通过MAUI的原生绑定调用.NET函数
              let result = YourDotNetClass.TargetFunction()
              reply(result)
          }
      }
      
    3. 在MAUI的macOS项目中注册XPC服务,确保应用启动时服务运行。
  • 发起调用的应用(客户端):
    按钮点击事件中通过MAUI的Platform API调用XPC客户端逻辑:
    private async void CallFuncButton_Clicked(object sender, EventArgs e)
    {
        string result = await Platform.InvokeOnMainThreadAsync(() => {
            // 调用原生XPC客户端代码获取结果
            return XPCClient.shared.invokeTargetFunction();
        });
        
        ResultLabel.Text = result;
    }
    
  • 替代方案:如果XPC配置复杂,可使用Apple事件,通过目标应用的Bundle ID发送触发事件,适合简单场景。

通用注意事项

  1. 两个应用都需完成代码签名(macOS下IPC会被系统阻止未签名应用);
  2. 跨进程调用中禁止直接操作UI,所有UI更新必须回到各自应用的主线程;
  3. 传递复杂参数时,需使用JSON等序列化方式确保数据能跨进程正确解析。

内容的提问来源于stack exchange,提问作者Shikhar Srivastava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 03:57:15