I suspect the problem is this:
- pointer to result size (int)
You should allocate it thusly:
a3 = FFI::MemoryPointer.new(:int, 1, false)
a3.write_int(a2.size)
If that C function is doing a conversion from an input string to an output string, the 'result size' probably needs to be initialized to the maximum size of the output string, and after the function is called, it will contain the actual number of bytes used in the output buffer. Thats a pretty common idiom, and one of the most common things people get wrong.
The reason why it sometimes worked, and sometimes did not was because the 'output size' was full of random garbage, since you were not initializing the a3 memory, so occasionally it would contain a positive integer value.