Rust FFI, call X from Rust


#1

Hello,

I just read Rust Once, Run Everywhere and I found it very interesting ! I didn’t knew about the possibility to use others languages in Rust by this way…

I found an example about how to do in C/C++ on Build Script.

If I have understood correctly, I can use Python, Ruby, or Javascript, in Rust. Do you have any examples of how to do ?

Thank you.


#2

No. What it’s saying is that Rust supports easy, direct FFI using the C calling convention both calling in and out. That is, you can write Rust code which can call C code (or anything which can expose a C-compatible interface) and you can write Rust code which can be called by C (or anything which can use a C-compatible interface).

Insofar as I know, there’s no easy way to turn Python, Ruby or JavaScript into a C-compatible interface. I know you can use something like ctypes to call Rust code from Python; I assume there’s something similar for Ruby and some variants of JavaScript.


#3

Last time I checked, it only worked the other way around for those languages. You can use Rust functions in Python, Ruby, or Javascript, but not functions declared in Python, Ruby, or Javascript in Rust.

There is crate to execute Lua code from Rust, though: https://github.com/tomaka/hlua


#4

You can go the other way in Ruby, at least: https://github.com/ruby/ruby/blob/trunk/doc/extension.rdoc#invoke-ruby-method-from-c


#5

Same in Python and just about any VM with a C API - which, in the case of JavaScript, notably excludes V8 (which only has a C++ API), but includes SpiderMonkey, JavaScriptCore, Duktape, etc. In general, google how to call X from C, and perform the same function calls from Rust instead.


#6

That’s not really the same thing, in context. This is about what FFI Rust itself supports natively. I mean, you could argue that Rust on Windows can call libraries written for Solaris on SPARC because “well, you can get an emulator, load the library in that, set up a network connection, then use this RPC library to make the call…”. I mean, yes, but it’s disingenuous to suggest that it’s in any way supported to the same degree as C.