views:

216

answers:

2

Quite-probably a silly question, as I don't know much about Java/Jython/JRuby/bytecode, but..

I stumbled across _why's unholy again today.. It allows you to output Python bytecode from Ruby code.. Basically allowing them to produce the same bytecode..

Jython outputs Java bytecode, as does JRuby.. Since these both compile to the same bytecode, does this mean you could potentially use any Python library from Ruby, and Ruby libraries from Python?

+3  A: 

There are two ways to do it. Both offer the ability to statically compile code and produce a real Java class from the script. Jython AFAIK in this case generates Java source code and then calls javac, via an jythonc script. But this requires compilation.

For both interpreters, you can call Java code from scripts, and you can embed the interpreter in a Java application.

For example, to call Java from Python:

>>> from java.util import Random
>>> r = Random()
>>> r.nextInt()
501203849

To embed JRuby interpreter in Java, you can do (note, there is a JSR223 based way too, this is the core one):

package vanilla;

import org.jruby.embed.ScriptingContainer;

public class HelloWorld {

    private HelloWorld() {
        ScriptingContainer container = new ScriptingContainer();
        container.runScriptlet("puts Hello world");
    }

    public static void main(String[] args) {
        new HelloWorld();
    }

You could do the same from Jyton (I guess you would need to give the jruby paths correctly):

import org.jruby.embed.ScriptingContainer
container = ScriptingContainer()
container.runScriptlet("puts Hello world")

The same can be done the other way around.

You won't get the whole ruby stdlib exported to the python interpreter by doing an import. You would need to precompile ruby's stdlib to bytecode in advance.

However with the technique described above, and adding a couple of helper scripts and defined interfaces, you can bridge specific functionality from one language to the other.

duncan
+3  A: 
Jörg W Mittag