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

React Native Windows C++ BLE模块注册构建错误及相关咨询

问题:React Native Windows C++ BLE模块构建错误与注册问题

环境详情

  • React Native版本:0.75.5
  • React Native Windows版本:0.75.13
  • C++编译器:MSVC(VS 2022)
  • 操作系统:Windows 10
  • 使用的蓝牙库:Windows.Devices.Bluetooth API

已完成操作

  • 用C++实现了BleModule原生模块
  • 使用REACT_MODULE(BleModule)完成模块注册
  • 尝试在ReactPackageProvider.cpp中引入该模块
  • 确保已安装必要依赖

尝试的代码

BleModule.h

#pragma once
#include "NativeModules.h"
#include <winrt/Windows.Devices.Bluetooth.h>
#include <winrt/Windows.Devices.Bluetooth.GenericAttributeProfile.h>
#include <winrt/Windows.Devices.Enumeration.h>

namespace winrt::SampleApp::implementation
{

// Declare the module to React Native
REACT_MODULE(BleModule)
struct BleModule
{
    // Default constructor (needed for React Native Windows)
    BleModule() = default;

    // Constructor with React Context
    BleModule(winrt::Microsoft::ReactNative::IReactContext const &reactContext);

    REACT_METHOD(StartScan);
    void StartScan();

    REACT_METHOD(ConnectToDevice);
    void ConnectToDevice(std::string deviceId);

private:
    winrt::Microsoft::ReactNative::IReactContext m_reactContext{nullptr};
};
}

BleModule.cpp

#include "pch.h"
#include "BleModule.h"

using namespace winrt;
using namespace Windows::Devices::Enumeration;
using namespace Windows::Devices::Bluetooth;

namespace winrt::SampleApp::implementation
{

// Default constructor (needed for React Native Windows)
BleModule::BleModule() {}

// Constructor to store React context
BleModule::BleModule(winrt::Microsoft::ReactNative::IReactContext const   &reactContext)
    : m_reactContext(reactContext) {}

void BleModule::StartScan()
{
    DeviceWatcher watcher = DeviceInformation::CreateWatcher(
        BluetoothLEDevice::GetDeviceSelector());

    watcher.Added([this](DeviceWatcher sender, DeviceInformation deviceInfo)
                  {
    auto deviceName = deviceInfo.Name().c_str();
    if (m_reactContext) {
        m_reactContext.CallJSFunction(
            L"RCTDeviceEventEmitter", L"emit", L"onDeviceFound", deviceName);
    } });

    watcher.Start();
}

void BleModule::ConnectToDevice(std::string deviceId)
{
    auto asyncOp = BluetoothLEDevice::FromIdAsync(winrt::to_hstring(deviceId));
    asyncOp.Completed([this](auto const &asyncInfo, auto const &status)
                      {
    if (status == Windows::Foundation::AsyncStatus::Completed) {
        auto device = asyncInfo.GetResults();
        if (device && m_reactContext) {
            m_reactContext.CallJSFunction(
                L"RCTDeviceEventEmitter", L"emit", L"onDeviceConnected", device.Name().c_str());
        }
    } });
}

 }

ReactPackageProvider.cpp

#include "pch.h"
#include "ReactPackageProvider.h"
#include "NativeModules.h"
#include "BleModule.h" // Ensure this is included

using namespace winrt::Microsoft::ReactNative;

namespace winrt::SampleApp::implementation
{

void ReactPackageProvider::CreatePackage(IReactPackageBuilder const &packageBuilder) noexcept
{
    AddAttributedModules(packageBuilder, true);
    packageBuilder.AddModule<L"BleModule">();
}

遇到的错误

构建失败,提示错误C2027:使用未定义类型'winrt::Microsoft::ReactNative::ModuleMethodInfo',需检查构建配置。

预期结果

C++ BleModule能在React Native Windows中被正确识别并注册,使JavaScript可调用其方法。

疑问

  1. 能否在Windows项目中使用C#类替代C++并完成注册?
  2. 是否需要额外步骤来正确暴露模块?
  3. React Native Windows中是否有特定的模块加载调试方式?
  4. 能否提供相关参考或可运行示例?

解答

一、解决C2027构建错误

1. 修正模块注册逻辑

你同时使用了AddAttributedModules和AddModule<L"BleModule">(),会导致重复注册。对于用REACT_MODULE宏标注的模块,只需保留AddAttributedModules(packageBuilder, true);,删除packageBuilder.AddModule<L"BleModule">();——属性宏会自动识别并注册模块。

2. 修复上下文初始化方式

React Native Windows C++模块不需要自定义带IReactContext的构造函数,需通过REACT_INIT宏指定初始化方法:
在BleModule.h中添加:

REACT_INIT(Initialize);
void Initialize(winrt::Microsoft::ReactNative::IReactContext const &reactContext)
{
    m_reactContext = reactContext;
}

同时删除自定义的带参数构造函数,保留默认构造函数即可。

3. 检查项目编译配置

  • 确保C项目的**C语言标准**设置为C++17或更高(React Native Windows依赖C++17特性)。
  • 确认附加包含目录包含$(ReactNativeWindowsDir)\ReactWindows\Shared和$(ReactNativeWindowsDir)\ReactWindows\Shared\NativeModules。

4. 验证头文件依赖

确认NativeModules.h来自正确路径,若路径错误,手动指定React Native Windows原生模块的头文件目录。

二、疑问解答

  1. 能否用C#替代C++实现模块?
    可以。React Native Windows支持C#原生模块,只需创建继承自ReactContextBaseModule的类,用[ReactModule]属性标注,再在ReactPackageProvider中注册即可。C#开发流程更简洁,BLE场景下性能与C++差异极小。

  2. 是否需要额外步骤暴露模块?
    除正确注册模块外,还需:

  • JS侧导入模块:import { NativeModules } from 'react-native'; const BleModule = NativeModules.BleModule;
  • 确保参数类型兼容(如std::string对应JS字符串,基本类型自动映射)。
  • 事件监听:JS侧通过NativeEventEmitter监听模块发送的事件,示例:
    import { NativeEventEmitter } from 'react-native';
    const bleEmitter = new NativeEventEmitter(BleModule);
    bleEmitter.addListener('onDeviceFound', (deviceName) => { /* 处理逻辑 */ });
    
  1. 模块加载调试方式
  • 在VS 2022中,给ReactPackageProvider::CreatePackage和模块的Initialize方法加断点,确认模块是否被加载初始化。
  • JS侧打印console.log(NativeModules);,查看是否包含BleModule。
  • 查看VS输出窗口的React Native分类日志,获取模块注册的详细信息。
  1. 参考与可运行示例
  • 官方C模块模板:通过npx react-native-windows-init --template cpp创建带C模块的项目,参考模板实现逻辑。
  • BLE功能示例:在官方模板基础上,替换模块逻辑为Windows.Devices.Bluetooth相关代码,同时在Package.appxmanifest中添加蓝牙权限(设置DeviceCapability为bluetooth)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 08:48:12