将字符串转换为字符串文字 C++

问题描述 投票:0回答:0

我想我需要将字符串转换为我正在使用的内置库的字符串文字。该函数采用 STRING_LITERAL,但我的变量是一个字符串。这是代码的最小版本..

  String firstString = "{ \"device_id\": ";
  temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR("{ \"device_id\": ")); // this works fine
  temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR(firstString )); // this fails

这是库中的 azure span 函数..

/**
 * @brief Returns an #az_span expression over a literal string.
 *
 * For example:
 *
 * `some_function(AZ_SPAN_FROM_STR("Hello world"));`
 *
 * where
 *
 * `void some_function(const az_span span);`
 *
 */
#define AZ_SPAN_FROM_STR(STRING_LITERAL) (az_span) AZ_SPAN_LITERAL_FROM_STR(STRING_LITERAL)

/**
 * @brief Returns a literal #az_span over a literal string.
 * The size of the #az_span is equal to the length of the string.
 *
 * For example:
 *
 * `static const az_span hw = AZ_SPAN_LITERAL_FROM_STR("Hello world");`
 *
 * @remarks An empty ("") literal string results in an #az_span with size set to 0.
 */
#define AZ_SPAN_LITERAL_FROM_STR(STRING_LITERAL)      \
  {                                                   \
    ._internal = {                                    \
      .ptr = (uint8_t*)(STRING_LITERAL),              \
      .size = _az_STRING_LITERAL_LEN(STRING_LITERAL), \
    },                                                \
  }


Compilation error: exit status 1

但是回溯到原来的我明白了..

error: invalid cast from type 'String' to type 'uint8_t*' {aka 'unsigned char*'}
  115 |       .ptr = (uint8_t*)(STRING_LITERAL),              \

如果我将 String 声明更改为 char*,我会得到一个不同的错误,该错误在库代码中对我来说意义不大。

az_span.h:100:45: error: expected ')' before string constant
  100 | #define _az_STRING_LITERAL_LEN(S) (sizeof(S "") - 1)

这是解释原因的代码

// Returns the size (in bytes) of a literal string.
// Note: Concatenating "" to S produces a compiler error if S is not a literal string
//       The stored string's length does not include the \0 terminator.
#define _az_STRING_LITERAL_LEN(S) (sizeof(S "") - 1)
c++ string type-conversion string-literals
© www.soinside.com 2019 - 2024. All rights reserved.