Get values of void pointer to an array -
// c lang #include <stdio.h> void func (void *ptr) { int *iptr = ptr; printf("{%d, %d, %d}\n", iptr[0], iptr[1], iptr[2]); } int main() { int ary[] = {111, 222, 333}; func(&ary); return 0; }
=> output: {111, 222, 333}
// vala public void func (void *ptr) { int *iptr = ptr; print("{%d, %d, %d}\n", iptr[0], iptr[1], iptr[2]); } void main(string[] args) { int[] ary = {111, 222, 333}; func(&ary); }
=> output: {155115112, 155115112, 3}
???
how values of void pointer array, in vala?
※ using void[]
better using void*
?
in example c code void* equivalent array of bytes (some chunk of memory), this:
public void func (uint8[] ptr) { int[] iptr = (int[]) ptr; print("{%d, %d, %d}\n", iptr[0], iptr[1], iptr[2]); } void main(string[] args) { int[] ary = {111, 222, 333}; func ((uint8[]) ary); }
this type unsafe however. vala uses addional hidden parameter length isn't set length in bytes, length in elements (but sizeof(int) != sizeof(char)
).
i advice find different way of doing whatever original problem is.
this question sounds typical xy problem.
using naked pointers highly discouraged in vala (indeed in every modern high level language). should use concepts containers, references, smart pointers, etc. instead.
edit: ok, here why original code doesn't work , how fix that:
you taking address of pointer here:
int[] ary = {111, 222, 333}; // ary pointer, &ary give int** func(&ary);
that shows how dangerous void*
is. there 2 ways fix (while still using void*
):
take address of first element:
int[] ary = {111, 222, 333}; func(&ary[0]);
cast array pointer:
int[] ary = {111, 222, 333}; func((void*) ary);
ps: void*
can have different meanings in other contexts (like opaque structure pointers or ref/out parameters or other ugly low level constructs).
Comments
Post a Comment