c - Postgres 用户定义类型并正确分配内存

标签 c postgresql memory-management

我正在为 postgres 编写一个扩展,其中包括创建一个新的可变长度基本类型,但是我在理解 SET_VARSIZE 的语义时遇到了一些困难。

采用以下示例代码,这并不能准确反射(reflect)我的用例,但它说明了要点。

typedef struct another_struct 
{
  char *a;
  char *b;
} another_struct;

typedef struct test_struct
{
  char vl_len_[4];
  another_struct *data;
} test_struct;

1)当为 test_struct 的新实例分配内存时,大概我可以简单地执行以下操作,并且它会考虑可变长度成员 vl_len_ 的大小?

test_struct *t = palloc0(sizeof(struct test_struct));

2)因为 another_struct 的两个成员都有可变长度,我想我还需要跟踪为这两个字段分配了多少内存,以便将正确的长度传递给 SET_VARSIZE?

3)调用 SET_VARSIZE 时是否还需要考虑 another_struct 指针的大小?

我认为对 SET_VARSIZE 的最终调用看起来像这样

SET_VARSIZE(t, sizeof(struct test_struct) + sizeof(struct another_struct) + a_and_b_length);

这接近正确吗?对于任何错误,我深表歉意,我对 C 语言编程相当陌生。

谢谢

最佳答案

仅使用常规指针无法做到这一点。所有内存必须放在 size 成员之后。

typedef struct another_struct 
{
  char a[FLEXIBLE_ARRAY_MEMBER];
  char b[FLEXIBLE_ARRAY_MEMBER];
} another_struct;

typedef struct test_struct
{
  char vl_len_[4];
  another_struct data;
} test_struct;

现在您必须知道数据的实际大小。

test_struct *t = palloc0(VARHDRSZ + size_of_a + size_of_b);
SET_VARSIZE(t, VARHDRSZ + size_of_a + size_of_b );
memcpy(t->data.a, src_a, size_of_a);
memcpy(t->data.b, src_b, size_of_b);

文档中的示例只有一个字段,所以我只是假设它是这样工作的。 间接可能存在其他问题。 来源:https://www.postgresql.org/docs/current/xfunc-c.html

关于c - Postgres 用户定义类型并正确分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54173021/

相关文章:

database - 从具有 NULL 值的 postgreSQL LEFT JOIN 查询中减去 2 列

c - 我的 C 代码中出现未知的 "delete"错误

c++ - 假人的高内存使用率

清理相机 osx 和 opencv

c - C 错误的确切行号?

sql - Postgres - 按 session 聚合用户事件

postgresql - Solr 可以用作缓存的替代品吗?

c++ - 在没有新运算符的情况下 segmentation 四叉树

c - 为什么我的数组打印不正确?

c malloc 错误代码 :3096