crystal-lang/crystal

Static Library

Closed this issue · 5 comments

Hey

How can I generate static library with crystal ? I'm trying to write a ruby extension, but with no luck.

cheers.

Hi!

We'd actually really like to write Ruby extensions in Crystal, and since Crystal is so similar to Ruby I think this is a very attractive idea.

We just put a small sample of how to do it in this repo. The Makefile generates a .bundle file, I guess for linux it would need to create a .so file so change it if you want to try it.

Do make irb and then Foo.new.foo(1) on there and it should return "From Crystal!! 1".

The repo is just a proof of concept, or a beginning of something that could eventually work. You have LibRuby bindings and with that you can declare classes, modules, methods, etc., as you would in C.

But we went a step futher: we have a macro that receives crystal code which generates the code you would need to call to define those things using the Ruby API. The repo has this as a sample:

ruby_extension "test_ruby",
class Foo
  def foo(a)
    "From Crystal!! #{a}"
  end
end

Note the comma at the end of the first line. We are actually passing a string and a whole AST node to the macro, which in turn is passed to a program that processes it and generates something like this:

redefine_main("Init_test_ruby") { |main| {{main}} }

_class = Ruby::Class.new "Foo"
_class.def "foo", 1, ->(self : LibRuby::VALUE, _a : LibRuby::VALUE, ) do
  a = Ruby::Value.new(_a)
  begin
    "From Crystal!! #{a}"
  end.to_ruby
end

Of course, the code is very simple and only handles that. Eventually it could support instance variables, modules, etc. Very clean and easy. And if the macros are too much or get in the way you could always write the code manually.

Being able to write Crystal extensions in Ruby would be amazing!

I think this isn't feasible right now, and because we have a GC it's less than ideal, so I'll close this.

@asterite This is an interesting proof of concept. I'm confused by your later comments though. Are you saying that writing ruby extensions in crystal doesn't make sense? Will it ever make sense? I was under the impression that this was a great use case for crystal-lang. Should I just go back to C or perhaps learn Rust for this purpose?

@elorest I've written a pretty well know library integrating Rust with Ruby : faster_path . Rust is a good way to go with that and I highly recommend it. As was stated earlier the GC is kind of the issue with mixing Crystal and Ruby. It's not that it doesn't work, but that you'd be running two of them. Rust has no GC.