Re: ffi : creating char **

  • From: Iwan Budi Kusnanto <ibk@xxxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Tue, 7 Jun 2016 17:27:55 +0700

On Mon, Jun 6, 2016 at 11:03 PM, Nagaev Boris <bnagaev@xxxxxxxxx> wrote:

On Mon, Jun 6, 2016 at 6:52 PM, Iwan Budi Kusnanto <ibk@xxxxxxxxxxxx> wrote:
Hi All,

How is the correct way to create `char **` with ffi?

I have done these ways:
-- create char[][]
local data = ffi.new("char["..k.."]["..m.."]")

-- cast it when calling C function
ffi.cast("char **", data)

But it doesn't work for me, i got segmentation fault error.


--
Iwan Budi Kusnanto


Hi,

char** and char[k][m] are different data structures.

char** is a pointer to pointer to char

char[k][m] is 2-dimensional array of char, which is stored as char[m]
repeated k times and can be casted to char* not to char**

Hi Boris, thanks for the response.

I managed to make it looks work by using
```
local data = ffi.new("char *[?]", k)
for i = 0, k - 1 do
      coding_ptrs[i] = ffi.new("char[?]", block_size)
end
```

But i am still not sure if this is the right way because
-  it doesn't always work, i.e., only works when size less than some value.
http://lua-users.org/lists/lua-l/2011-02/msg00287.html said that it
is not the right way.

Any clue about this?
The C code itself is:
```

coding = (char **)malloc(sizeof(char*)*m);
for (i = 0; i < m; i++) {
        coding[i] = (char *)malloc(sizeof(char)*blocksize);
         if (coding[i] == NULL) { perror("malloc"); exit(1); }
}
```

Thanks


--


Best regards,
Boris Nagaev




-- 
Iwan Budi Kusnanto

Other related posts: