简而言之,我的问题是:我正在构建一个动态内存管理器,它包含各种不同类型的对象。我用标记标记每种不同类型的对象,并且为了使内存调试更容易,我希望这些标记作为我可以读取的四字节字符串出现在内存中。但是,为了有效地打开这些值,我还想将它们视为无符号32位整数。
目前,对象的定义如下:
/**
* an object in cons space.
*/
struct cons_space_object {
char tag[TAGLENGTH]; /* the tag (type) of this cell */
uint32_t count; /* the count of the number of references to this cell */
struct cons_pointer access; /* cons pointer to the access control list of this cell */
union {
/* if tag == CONSTAG */
struct cons_payload cons;
/* if tag == FREETAG */
struct free_payload free;
/* if tag == INTEGERTAG */
struct integer_payload integer;
/* if tag == NILTAG; we'll treat the special cell NIL as just a cons */
struct cons_payload nil;
/* if tag == REALTAG */
struct real_payload real;
/* if tag == STRINGTAG */
struct string_payload string;
/* if tag == TRUETAG; we'll treat the special cell T as just a cons */
struct cons_payload t;
} payload;
};
标签是四个字符串常量,例如:
#define CONSTAG "CONS"
我希望能够如此
switch ( cell.tag) {
case CONSTAG : dosomethingwithacons( cell);
break;
但当然你不能打开一个字符串。但是,由于这些是四字节字符串,因此它们可以在内存中读取为32位无符号整数。我想要的是一个宏,给定一个字符串作为参数,返回一个unsigned int。我试过了
/**
* a macro to convert a tag into a number
*/
#define tag2uint(tag) ((uint32_t)*tag)
但它实际上做的是返回该地址第一个字符的ASCII值 - 即
tag2uint("FREE") => 70
这是' F'。
的ascii代码有人为我解决这个问题吗?自从我在C中写下任何严肃的事情以来已经二十年了。
答案 0 :(得分:3)
#define tag2uint(tag) ((uint32_t)*tag)
表示“取消引用tag
(在您的示例中获取'F'
),然后将其转换为uint32_t
。”
你想做的应该是
#define tag2uint(tag) (*(uint32_t*)tag)
这意味着“将tag
视为uint32_t
的指针,然后取消引用它。”