When I was writing previous post about using FFI to “outsource” some work from Ruby to D, I was pretty sure that this is only one-way option: you call a D function with some parameters and obtain final result. It turns out, though, that FFI is much more awesome than I thought and you can use callbacks to enhance coöperation between those two. Using that I extended my prime example so now it prints every non-prime number met alongway too.
First of all, we have to change our D code:
A second argument is added to
firstPrime function. It is any function that accepts one
long and returns nothing. Then we call it in every place where we are sure that our current candidate for a prime is actually not a prime with simple
Now, to the Ruby side:
This is how we register callbacks. Not really much of a magic here, but now we can call
And the result is:
All this is getting more and more interesting for me. D seems to be quite powerful (although right now probably loses to Rust in terms of popularity), multiplatform and relatively easy to combine with Ruby. It might be really useful when your Ruby application gets too slow because of many computations and you don’t feel like writing cumbersome C code.