Crystal C bindings: argument const unsigned char **

256 Views Asked by At

This is a signature of a C function that I'm trying to use (which produces an array of binary data):

long get_output( const unsigned char ** );

And I map it with:

fun output = get_output( UInt8** ): Int32

In C a working example to use it do:

const unsigned char * data;
get_output( &data );

But in Crystal:

data = uninitialized UInt8
MyLib.output( pointerof( pointerof( data ) ) ) # ERR: pointerof of pointerof not allowed
1

There are 1 best solutions below

0
On BEST ANSWER

This works:

data = uninitialized UInt8*
MyLib.output(pointerof(data))

Note that the argument you have is UInt8** so you need to declare a variable of type UInt8*.

However, Crystal supports this idiom really nicely, with the out keyword: https://crystal-lang.org/docs/syntax_and_semantics/c_bindings/out.html

MyLib.output(out data)
# use data

This last way is preferred because it's more DRY, you don't have to repeat the type.

Also be careful, long usually maps to Int64. In general there are good aliases under LibC, for example LibC::Char, LibC::Long, etc.