【问题标题】:Using a data structure from my C header in assembly file在汇编文件中使用我的 C 头文件中的数据结构
【发布时间】:2020-11-04 15:38:41
【问题描述】:

我实际上正在学习汇编语言(在 Linux 上工作),我的问题是:我有一个 C 标头,其中包含这样的链表

typedef struct s_list
{
  void *data;
  struct s_list *next;
} t_list;

我想要做的是在我的程序集 .s 文件中与我想在我的 C 程序中使用的函数进行交互, 例如在我的 C 程序中:

void *someData = someValue;
t_list *someList = NULL;
someList = listAddBack(somelist, someData);

我可以直接在我的程序集文件中包含我的头文件,还是我必须在我的程序集文件中声明与struc 相同的结构,然后从这里执行我的函数?抱歉,我不是以英语为母语的人,英语不好。

【问题讨论】:

    标签: c assembly struct nasm


    【解决方案1】:

    Assembly 没有像 struct 这样的约定,为了使用 C 中的结构,您必须首先知道您的 C 程序如何在内存中布局结构,由于结构重新排序,这些结构在实现甚至编译之间可能会有很大差异。您必须在 Assembly 中手动构造和读取结构。

    但是,如果您只是想使用示例中列出的结构,那么您很幸运,因为 C 标准规定结构的第一项始终是内存中的第一项,并且因为其中只有两项struct 你可以确定下一个项目在哪里。

    假设我们正在处理 x86 并且 edi 是指向您的 s_list 的指针

    mov eax, DWORD [edi] ; eax now holds the data pointer
    mov ebx, DWORD [edi + 4] ; 4 bytes is the size of a dword, which in turn is the size of all pointer types in x86, so if we look 4 bytes beyond the pointer to the `s_list` we will find the value for the pointer to next
    

    如果您想以另一种方式思考这个问题,请尝试查看您用 C 编写的代码,并在不使用 struct 的任何地方编写它,这将使您了解它在 Assembly 中的工作原理。

    【讨论】:

    • 谢谢你的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    • 2018-01-29
    • 1970-01-01
    • 2013-10-15
    • 2022-06-13
    • 1970-01-01
    相关资源
    最近更新 更多