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

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

本文关键字:字符串 用于 C++ std 转换 Delphi      更新时间:2023-10-16

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

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

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

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);
}

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

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

所以我决定将我的数据转换为8Bit AnsiString并发送,但这次我看到Delphi不再支持移动编译器中的AnsiChar和Ansistring(你可以在这里和这里阅读)。

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

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

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

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