将 Delphi 的字符串转换为 C++ 的 std::string

Converting String for Delphi to std::string for C++

我正在开发一个设备 (ESP32),有一个 rxValue 变量定义如下;

std::string rxValue = pCharacteristic->getValue(); <- ESP32 (C++) side

但我需要通过 SetValueAs... 方法从 Delphi App 发送数据(字符串或字符)但是当我使用

Characteristics.SetValueAsString('b'); <- Delphi side (but problematic)

编辑:我在此处添加 SetValueAsString 过程

procedure TBluetoothGattCharacteristic.SetValueAsString(const AValue: string; IsUTF8: Boolean);
begin
  if IsUTF8 then
    Value := TEncoding.UTF8.GetBytes(AValue)
  else
    Value := TEncoding.Unicode.GetBytes(AValue);
end;

Arduino 串口监视器显示一个奇怪的字符(方块)并且无法执行命令。

    for (int i = 0; i < rxValue.length(); i++) {   <- ESP32 (C++) side
      Serial.print(rxValue[i]);
    }

    if (rxValue.find("a") != -1) { 
      digitalWrite(LED, HIGH);
    }

因此,将字符串从Delphi发送到C++(ESP32板)的方式是什么std::string。另外(我不想单独问一个小问题。) rxValue 与 string 的精确比较方式是什么?我的意思是,如果 rxValueabcdef 完全相同,则执行命令? 马上谢谢..

深入研究后,问题变得更加复杂。正如@RemyLebeau 指出的那样,主要问题是 8 位/16 位字符串不兼容,@David Heffernan 是正确的,因为您不能使用 std::string 进行跨编程语言的互操作。

所以我决定将我的数据转换为 8 位 AnsiString 并发送,但这次我看到 Delphi 不再支持移动编译器中的 AnsiChar 和 AnsiString(您可以阅读 here and here ).

所以我不能在 Delphi 移动设备中使用 8 位字符串(很多人向 "why" 询问 Embarcadero,因为这意味着您不能使用使用 8 位的设备(许多物联网设备) ) 但谢天谢地,有一些好人用自定义库解决了这个问题(你可以找到来源 here)。

将此库添加到我的应用程序并执行如下命令后,问题已解决;

Characteristics.SetValueAsString(RawByteString('b'));

但答案是:你不能这样使用std::string,它不适合互操作。