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

如何搭建UWP C#库与React Native的通信桥接

在React Native Windows中调用UWP C#库的实现方案

一、UWP端Native Module实现

首先在你的React Native Windows项目的UWP工程中集成C#库,并封装Native Module:

  1. 添加UWP库引用
    右键RN Windows项目中的UWP工程 → 选择「添加」→「引用」→ 找到并选中你的UWP C#库,完成引用。

  2. 创建自定义Native Module类
    新建一个C#类,继承NativeModuleBase并实现IReactMethodProvider接口,用[ReactMethod]标记需要暴露给JS层的方法:

using ReactNative.Bridge;
using System.Reflection;
using System.Threading.Tasks;

namespace YourAppUWP.Modules
{
    public class UWPLibraryBridge : NativeModuleBase, IReactMethodProvider
    {
        private readonly YourUWPCustomLibrary _library;

        public UWPLibraryBridge()
        {
            _library = new YourUWPCustomLibrary();
        }

        // 暴露给JS的异步方法
        [ReactMethod]
        public void ExecuteLibraryFunction(string input, IReactPromise<string> promise)
        {
            try
            {
                // 调用UWP库的核心方法
                string result = _library.YourLibraryMethod(input);
                promise.Resolve(result);
            }
            catch (Exception ex)
            {
                promise.Reject("LIBRARY_ERROR", ex.Message, ex);
            }
        }

        // 实现接口,返回所有标记了ReactMethod的方法
        public IEnumerable<MethodInfo> GetMethods()
        {
            return GetType()
                .GetMethods(BindingFlags.Public | BindingFlags.Instance)
                .Where(m => m.GetCustomAttributes(typeof(ReactMethodAttribute), false).Any());
        }
    }
}
  1. 注册Native Module
    在UWP工程的App.cs中,重写CreateReactNativeHost方法,配置服务注册你的模块:
protected override ReactNativeHost CreateReactNativeHost()
{
    return new ReactNativeHost(this)
    {
        // 保留原有配置(如JS入口文件等)
        MainComponentName = "YourApp",
        ConfigureServices = services =>
        {
            // 注册自定义模块
            services.AddSingleton<IReactModuleProvider, UWPLibraryBridge>();
        }
    };
}

二、React Native JS端调用

封装JS工具类,调用Native Module暴露的方法:

  1. 封装调用工具
    新建UWPLibraryBridge.js:
import { NativeModules } from 'react-native';

// 对应UWP端注册的模块类名
const { UWPLibraryBridge } = NativeModules;

export default {
  // 封装异步调用方法
  callLibraryMethod: async (input) => {
    try {
      const result = await UWPLibraryBridge.executeLibraryFunction(input);
      return result;
    } catch (error) {
      console.error('UWP库调用失败:', error);
      throw error;
    }
  },
};
  1. 在RN组件中使用
import React, { useState } from 'react';
import { View, Button, Text } from 'react-native';
import UWPLibraryBridge from './UWPLibraryBridge';

const App = () => {
  const [result, setResult] = useState('');

  const handleCallLibrary = async () => {
    try {
      const res = await UWPLibraryBridge.callLibraryMethod('测试输入');
      setResult(res);
    } catch (err) {
      setResult('调用失败');
    }
  };

  return (
    <View style={{ padding: 20 }}>
      <Button title="调用UWP C#库" onPress={handleCallLibrary} />
      <Text style={{ marginTop: 10 }}>调用结果: {result}</Text>
    </View>
  );
};

export default App;

三、关键注意事项

  • 确保UWP库的目标版本与RN Windows项目的UWP目标版本一致,避免版本兼容问题。
  • 涉及UI线程的操作(如UWP库需要更新UI),需通过Dispatcher.RunAsync切换到UI线程执行:
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {
        // 执行UI相关操作
    });
    
  • 异步方法必须通过IReactPromise传递结果,JS端用async/await接收;同步方法可直接返回值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 10:55:19