How can I call a built-in compiler function in Ruby?

89 views Asked by At

I'm working in Ruby, and realized that it would be incredibly beneficial to be able to use some of the built-in gcc functions (and x86 architecture built-ins for that matter as well). It seems like having to write an extension to use these is impractical, so I was wondering if there was a way I could call built-ins. For example, if I wanted to call int __builtin_popcount(unsigned int), on a number in Ruby, is there a way I could somehow do

a = rand(1..10000)
__builtin_popcount(a)

I know that I obviously can't do something that basic, but is there a way that I could include gcc and x86 architecture built-ins in Ruby?

1

There are 1 answers

0
Jörg W Mittag On

It is not quite clear what you want to do.

If you want to call into GCC, you could wrap libgcc in a C extension and design a Ruby API for it.

If you want to generate native code using GCC dynamically, that is currently not possible AFAIK. There is a project for a JIT compiler library based on GCC, but I don't know what its status is. You could wrap that library into a C extension and design a Ruby API for it. At any rate, you will also have to modify the Ruby implementation you are using to be able to link dynamically generated native code with your Ruby code. (And on some implementations that is simply impossible, e.g. on Opal, which is a pure static compiler.)

And of course, not all Ruby implementations actually support C extensions; they are a non-standard feature of YARV and are not guaranteed to work or even exist on other implementations.