[Haskell-cafe] FFI nested structs - malloc - free

Anatoly Zaretsky anatoly.zaretsky at gmail.com
Tue May 5 14:37:45 UTC 2015


On Tue, May 5, 2015 at 4:22 PM, Michael Jones <mike at proclivis.com> wrote:
>
> In my case, the FFI calls ioctl, which calls i2cdev_ioctl, which calls i2cdev_ioctl_rdwr.
>
> The only function that can assume anything about the structure is i2cdev_ioctl_rdwr, which as you can see below copies the data, but does not free it.

This is a useful bit of context: generally the kernel does not use
passed-in user pointers after a system call returns, so you might not
need malloc/free at all.

Consider this C code sample (don't know anything about this particular
API, so the example can be horribly wrong):

int some_i2c_bus_transaction(int i2c_dev_fd)
{
    struct i2c_rdwr_ioctl_data req;
    struct i2c_msg msgs[2];
    __u8 read_buf[64], write_buf[8];
    write_buf[0] = 0x12;
    write_buf[1] = 0x34;
    write_buf[2] = 0x56;
    msgs[0].flags = I2C_M_RD;
    msgs[0].buf = write_buf;
    msgs[0].len = 3;
    msgs[1].buf = read_buf;
    msgs[1].len = sizeof(read_buf);
    req.nmsgs = 2;
    req.msgs = msgs;
    return ioctl(i2c_dev_fd, I2C_RDWR, &req);
}

If your usage is similar to this, you might consider using alloca*
functions which are closer to C's automatic stack allocations than
heavy-weight "low-level" heap allocations. See the first example in
https://wiki.haskell.org/Foreign_Function_Interface#Memory_allocation

--
Tolik


More information about the Haskell-Cafe mailing list