c - 为什么不能在 C 中直接将 number 转换为 struct?

标签 c struct

我将结构定义为:

typedef struct cr3_page_entry
{
   uint64_t ignored     : 2;   // ignored
   uint64_t pwt         : 1;   // page-level write-through; indirectly determines the memory type used to access the PML4 table during linear-address translation (see Section 4.9.2)
   uint64_t pcd         : 1;   // page-level cache disable; indirectly determines the memory type used to access the PML4 table during linear-address translation (see Section 4.9.2)
   uint64_t ignored2    : 7;   // ignored
   uint64_t address     : 53;  // rest is address up to MAXPHYADDR, then zeros
} cr3_page_entry_t;

这是一个 uint64_t,如果您查看它(64 位大小的结构)。现在,我有一个从中返回这样一个数字的汇编函数

extern uint64_t get_active_page();

但是,我不能直接转换为它:

cr3_page_entry_t entry = (cr3_page_entry_t) get_active_page();

因为我得到一个错误:

memory/paging.c:19:2: error: conversion to non-scalar type requested
  cr3_page_entry_t entry = (cr3_page_entry_t) get_active_page();

这可以在不为某些指针转换创建另一个堆栈变量的情况下完成吗?

最佳答案

uint64_tcr3_page_entry_t 结构定义union。然后分配给uint64_t成员。

typedef union _cr3_u
{
   uint64_t i;
   cr3_page_entry_t str;
} cr3_u;

cr3_u my_data;

my_data.i = get_active_page();

关于c - 为什么不能在 C 中直接将 number 转换为 struct?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34060778/

相关文章:

c - 指向结构体数组的指针增量失败

c++ - 哪些标准允许在 C 和 C++ 中使用匿名结构和 union ?

c - 传递struct的字段名在函数内部访问

c++ - 在条件表达式中使用时,gcc 或其他编译器是否自动将按位或转换为 bool 值或?

c - C语言中fgets函数的使用

go - 结构声明中的文字值

c - 如何找出内核结构的字段偏移量?

将值写入其他变量后,C 在函数中释放 int 数组

c - 将 unsigned long 转换为 int 时是否有获得垃圾值的风险?

连接四个,检查 C 中的获胜者