NIFs vs Jinterface

What’s the difference between NIFs and Jinterface?

From what I can tell, NIFs are for implementing a function natively, with C or, Rust along with Rustler.

Jinterface provides support for using a Java Service along with an Erlang service, by providing classes and methods to create new nodes, new processes and pass and receive messages. Additionally it provides classes for working with Erlang datatypes from within Java.

Apart from the fact that NIFs target native languages, or pretty much anything that implements a C ABI, and that Jinterface targets languages on the JVM, what exactly is the difference between the 2? How could I use a function implemented in Java from Elixir (JNI + NIFs?)?

What’s the difference between NIFs and Jinterface?
Apart from the fact that NIFs target native languages, or pretty much anything that implements a C ABI, and that Jinterface targets languages on the JVM, what exactly is the difference between the 2?

Well, these are two different tools for two different tasks. From my experience with jinterface, I can tell that it is a little bit outdated for today, because it supports strings as charlists and etc.

I’d suggest avoiding using Jinterface. While NIFs are used to extend BEAM with extremely fast native functions, Jinterface is mostly used just as a JVM<->BEAM communication tool. In 2022, it is better to wrap both JVM and Erlang programs into services and to communicate via HTTP or one of morden rpc protocols

You cannot call a Java function from Erlang directly. However, you communicate to a Java process from Erlang through a Port process (the name is confusing). This is a separate process that the Erlang VM spawns locally. You can use something like a fat jar and spawn the port process when your own application starts. However Ports are a bit tricky to work with directly. An alternative is to use the library Exile. Exile provides some great protections that you’d otherwise need to add yourself.

With the Port you can use the JInterface library’s message serialization code to create responses that Erlang can directly decode, or rely on something more ‘modern’ like a protobuf or JSON blob. Ports are flexible.

1 Like