dart 中结构的数组成员:ffi

问题描述

我想在我的颤振项目中使用 Bob Jenkins rng https://burtleburtle.net/bob/rand/isaacafa.html

这里我们有一个包含 2 个静态缓冲区的结构

/* context of random number generator */
struct randctx
{
  ub4 randcnt;
  ub4 randrsl[RANDSIZ];
  ub4 randmem[RANDSIZ];
  ub4 randa;
  ub4 randb;
  ub4 randc;
};
typedef  struct randctx  randctx;

现在在 dart:ffi 中,一个 Struct 类只能有 int、double 和 Pointer 的成员,并进行适当的装饰。 但是,我无法用给定的 NativeTypes 描述这个结构。

class _Rand_context extends Struct {
  @Uint32()
  int counter;
  Pointer<Uint32> result;
  Pointer<Uint32> mem;
  @Uint32()
  int a;
  @Uint32()
  int b;
  @Uint32()
  int c;
}

因为 ctx.result.asTypedList(256) 崩溃了。所以我所做的只是将结构中的数组更改为指针并以这种方式初始化:

randctx* create_context() {
  randctx* ctx = (randctx*)malloc(sizeof(randctx));
  ub4* mem = (ub4*)malloc(sizeof(ub4) * RANDSIZ);
  ub4* res = (ub4*)malloc(sizeof(ub4) * RANDSIZ);
  ctx->randa=ctx->randb=ctx->randc=(ub4)0;
  memset(res,sizeof(ub4) * RANDSIZ);
  memset(mem,sizeof(ub4) * RANDSIZ);
  ctx->randmem = mem;
  ctx->randrsl = res;
  randinit(ctx,TRUE);

  return ctx;
}

这可以由 asTypedList 处理,但我不熟悉 GC 如何处理结构,我担心 mem 和 result 不会被释放。是这种情况吗?或者我应该怎么做?

解决方法

想出了一些东西: 保留原始结构,但为缓冲区添加 2 个额外的指针

struct randctx
{
  ub4 randcnt;
  ub4 randrsl[RANDSIZ];
  ub4 randmem[RANDSIZ];
  ub4* rslptr;
  ub4* memptr;
  ub4 randa;
  ub4 randb;
  ub4 randc;
};
typedef  struct randctx  randctx;

randctx* create_context() {
  randctx* ctx = (randctx*)malloc(sizeof(randctx));
  ctx->randa=ctx->randb=ctx->randc=(ub4)0;
  memset(ctx->randrsl,sizeof(ub4) * RANDSIZ);
  memset(ctx->randmem,sizeof(ub4) * RANDSIZ);
  ctx->memptr = ctx->randmem;
  ctx->rslptr = ctx->randrsl;
  randinit(ctx,TRUE);

  return ctx;
}

并提供指向 asTypedList 的指针。似乎工作,事情都在一个地方,希望没有悬空的所有权。可以忍受额外的 16 个字节。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...