【问题标题】:Dynamically create a C structure memory content with proper alignment动态创建正确对齐的 C 结构内存内容
【发布时间】:2013-12-23 17:01:12
【问题描述】:

C/Invoke 库包含用于动态调用 C 函数和在堆上动态创建 C 结构的函数,而这些函数又可以传递给动态创建的堆栈帧,代表动态函数调用。虽然该库的后一个功能正是我所需要的,但我不能使用该库,因为它旨在满足用例。我认为使用这个库会导致丑陋的代码。我需要的是如下一组函数

struct dyn_struct {
  int size;
  int members;
  char *bit_field;
};

int add_member_uint(struct dyn_struct *struct, unsigned int value);
int add_member_int(struct dyn_struct *struct, int value);
int add_member_float(struct dyn_struct *struct, float value);
[...]
int add_member_pvoid(DynStruct *struct; void *value);

更具体地说,我正在使用库 libffi 以使用结构作为参数动态调用动态加载的 C 库函数。我正在写一个小程序语言的解释器(Lua和C的结合,可能不是很有创意……)

【问题讨论】:

  • 你的问题是?具体点!
  • 就对齐而言,您应该使用#pragma pack(n) 来添加/删除填充。
  • 抱歉,不具体。我的问题是:你知道有一个库可以像我画的那样在堆内存中动态构建结构吗?

标签: c memory-management data-structures x86 x86-64


【解决方案1】:

我不确定我是否完全理解您要查找的内容,但是使用 libffi,如果您填充描述您的类型的 ffi_type 结构,那么第一次调用 ffi_prep_cif 时将填充 ffi_type 的大小和对齐字段。静态 initialize_aggregate() 函数对此负责。这可能是我们向用户公开的有用功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 2012-06-26
    • 2023-03-10
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    相关资源
    最近更新 更多