C宏将字符串转换为Pascal字符串类型 [英] C Macro to convert a string to a pascal string type

查看:65
本文介绍了C宏将字符串转换为Pascal字符串类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一些宏的想法,以将预处理器定义的字符串转换为pascal类型的字符串,然后能够使用该宏初始化const char数组等.

I would like some ideas for a macro to convert a preprocessor defined string to a pascal type string and then be able to use the macro to initialize const char arrays and the like.

这样的事情会很棒:

#define P_STRING_CONV(str) ...???...

const char *string = P_STRING_CONV("some string");

struct
{
    char str[30];
    ...
}some_struct = {.str = P_STRING_CONV("some_other_string")};

我已经尝试过这样的事情:

I already tried something like this:

#define DEFINE_PASCAL_STRING(var, str, strlen) struct {uint8_t len; char content[strlen-1];} (var) = {sizeof(str)-1, (str)}

(strlen参数可以删除,但我需要定义大小.)

(The strlen parameter could be removed, but I need a defined size.)

这很好,但是不能用于初始化结构中的元素.对于const char数组,我需要将其强制转换为其他变量.

That works fine, but cannot be used to initialize elements in a struct. And for const char arrays I need to cast it to some other variable.

有什么好主意吗?

推荐答案

您可以将宏分为两部分:

You could split the macro into two:

#define PASCAL_STRING_TYPE(size) struct { unsigned char len; char content[(size) - 1]; }
#define PASCAL_STRING_INIT(str) { .len = sizeof(str) - 1, .content = (str) }

然后像这样使用它:

static const PASCAL_STRING_TYPE(100) foo = PASCAL_STRING_INIT("foo");

struct bar {
   int answer;
   PASCAL_STRING_TYPE(100) question;
};
static const struct bar quux = {
    .answer = 42,
    .question = PASCAL_STRING_INIT("The Answer")
};

(未经测试.)

这篇关于C宏将字符串转换为Pascal字符串类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆