如何在NASM中正确创建结构体数组?
在NASM中正确创建结构体数组的方法
背景
我正在用NASM为一个项目编写简单的CLI解析器,通过NASM的结构体(struc)定义参数数量、回调函数和子命令名称。单个结构体实例能正常运行,但定义多个实例时出现了问题。
项目代码
argparser.inc
struc command .arg_count: resd 1 .name: resq 1 .fn: resq 1 endstruc
arun.asm
%include "argparser.inc" ... section .data commands_struct: istruc command at command.arg_count, dd 2 at command.name, dq command_names.create at command.fn, dq create iend
错误情况
上述代码可正常运行,但添加第二个结构体实例后(如下所示)出现编译错误:
错误代码(arun.asm)
%include "argparser.inc" ... section .data commands_struct: istruc command at command.arg_count, dd 2 at command.name, dq command_names.create at command.fn, dq create iend istruct command ; 此处为拼写错误,正确指令是istruc at command.arg_count, dd 1 at command.name, dq command_names.start at command.fn, dq start iend
错误信息
arun.asm:31: error: parser: instruction expected arun.asm:32: error: `%$strucname': context stack is empty arun.asm:32: error: `%$strucstart': context stack is empty arun.asm:32: error: `%$strucname': context stack is empty arun.asm:32: error: `%$strucstart': context stack is empty arun.asm:32: error: expression syntax error arun.asm:33: error: `%$strucname': context stack is empty arun.asm:33: error: `%$strucstart': context stack is empty arun.asm:33: error: `%$strucname': context stack is empty arun.asm:33: error: `%$strucstart': context stack is empty arun.asm:33: error: expression syntax error arun.asm:34: error: `%$strucname': context stack is empty arun.asm:34: error: `%$strucstart': context stack is empty arun.asm:34: error: `%$strucname': context stack is empty arun.asm:34: error: `%$strucstart': context stack is empty arun.asm:34: error: expression syntax error arun.asm:35: error: `%$strucname_size': context stack is empty arun.asm:35: error: `%$strucstart': context stack is empty arun.asm:35: error: `%$strucname_size': context stack is empty arun.asm:35: error: `%$strucstart': context stack is empty arun.asm:35: error: expression syntax error arun.asm:35: error: `%pop': context stack is empty
解决方案
1. 修正拼写错误
错误的核心原因是第二个结构体实例使用了错误的指令名istruct,NASM中正确的结构体实例化指令是istruc(缺少字母t)。
2. 正确创建结构体数组
要在NASM中创建结构体数组,只需在.data段中连续定义多个istruc/iend块即可,它们会在内存中连续排布,形成数组。修正后的代码如下:
%include "argparser.inc" ... section .data commands_struct: ; 第一个结构体实例 istruc command at command.arg_count, dd 2 at command.name, dq command_names.create at command.fn, dq create iend ; 第二个结构体实例,直接接续在第一个之后 istruc command at command.arg_count, dd 1 at command.name, dq command_names.start at command.fn, dq start iend
3. 访问数组元素
你可以通过NASM自动生成的结构体大小常量command_size来访问数组中的元素,例如访问第二个元素的arg_count字段:
; 计算第二个元素的地址:commands_struct + command_size mov eax, [commands_struct + command_size + command.arg_count]
内容的提问来源于stack exchange,提问作者itasahobby
相关产品推荐
相关产品推荐

