Learn Julia Β· 14/15

Interoperability: Calling Other Languages

9 min read

Welcome, Julia programmer! You've been honing your skills in this beautiful, fast language. But what happens when you're working on a team, and your colleagues have already built amazing tools in Python, C, or R? Do you spend months rewriting everything in Julia? Absolutely not!

The Problem: In the real world, projects are rarely built in a single language. There's a vast universe of incredible, battle-tested code written in other languages. A data science team might have a Python expert who built a data-cleaning pipeline, a C veteran who wrote a lightning-fast simulation core, and a statistician who has a suite of models in R. How can you, the Julia developer, leverage all this existing work without leaving your beloved Julia environment?

The Solution: Julia was designed from the ground up to be a fantastic "glue" language. It has first-class support for interoperability, allowing you to call functions and share data with other languages seamlessly. This isn't a clunky afterthought; it's a core superpower of Julia. Let's learn how to become the ultimate team player by making Julia talk to its neighbors.


🐍 1. Integrating with Python using PythonCall.jl

Python has a colossal ecosystem, especially for data science (pandas, scikit-learn) and machine learning (PyTorch, TensorFlow). It would be a shame not to use it. PythonCall.jl is your golden ticket to the entire Python universe.

Getting Started πŸ› οΈ

First, you need to add the package. Open the Julia REPL (by typing julia in your terminal), press ] to enter the package manager, and then type:

julia
(v1.10) pkg> add PythonCall

Now, let's get it set up. PythonCall.jl is incredibly smart. When you first use it, it will try to find a Python installation on your system. If you want to be specific, you can tell it exactly which Python executable to use.

By default, PythonCall.jl uses another fantastic package, CondaPkg.jl, to manage its own little Python environment specific to your Julia project. This is amazing because it keeps everything clean and isolated. You don't have to worry about messing up your system's Python installation.

Calling Python: A Practical Example πŸ§‘β€πŸ”¬

Imagine our colleague "Python Pete" gave us a simple Python function to find unique words in a text.

Python Code (pete_utils.py):

python
import re

def find_unique_words(text):
  """Finds all unique, lowercased words in a given text."""
  words = re.findall(r'\b\w+\b', text.lower())
  return sorted(list(set(words)))

Now, let's call this from Julia.

Julia Code:

julia
using PythonCall

# Import the Python 're' module. The result is a PyObject.
re = pyimport("re")

# We can call functions on this PyObject just like in Python.
words = re.findall("[a-zA-Z]+", "PythonCall.jl is profoundly useful!")
println(pyconvert(Vector{String}, words)) # Convert the Python list to a Julia Vector

# Let's import Pete's custom module.
# First, we need to add the current directory to Python's path.
sys = pyimport("sys")
sys.path.append(".") # Add current directory

# Now import pete_utils
pete_utils = pyimport("pete_utils")

# Let's use his function!
my_text = "Julia is fast, Python is fast, calling Python from Julia is fast-inating!"
unique_words = pete_utils.find_unique_words(my_text)

# The result 'unique_words' is a PyObject (a Python list).
# We can convert it to a Julia type to work with it more naturally.
julia_words = pyconvert(Vector{String}, unique_words)

println("\nWords found by Pete's Python function:")
for word in julia_words
    println("- ", word)
end

What's happening here?

  1. pyimport("module_name") is your gateway. It loads a Python module and gives you back a special PyObject that acts as a remote control for the real Python object.
  2. You can call methods and access attributes on this PyObject using the familiar dot syntax (e.g., re.findall).
  3. Data types are often converted automatically. Julia strings become Python strings, numbers become numbers, etc.
  4. For more complex types, pyconvert(JuliaType, python_object) is your best friend. It explicitly converts a Python object back into a native Julia type you can work with.
  5. Zero-Copy Magic: For big data like large numerical arrays, PythonCall.jl is smart enough to share the underlying memory instead of copying it. This means you can pass huge arrays between Julia and Python almost instantly!

🧠 Under the Hood: PythonCall.jl starts and maintains a Python interpreter session inside the Julia process. When you pyimport or call a function, it sends the command to this interpreter and translates the result back for you. It's like having a live Python translator whispering in Julia's ear.


βš™οΈ 2. Calling C and Fortran Code Directly (ccall)

Sometimes, you need raw, unadulterated speed. For decades, the most performance-critical code in science and engineering has been written in C and Fortran. These languages compile down to incredibly efficient machine code.

The Problem: Your team has a 20-year-old, battle-hardened C library that performs a critical physics calculation. It's legendary for its speed. Rewriting and validating it in Julia would be a massive, risky project. How can you tap into this legendary speed directly?

The Solution: Julia has a beautiful, built-in function called ccall. This isn't a package; it's a fundamental part of the language. It allows you to call functions directly in compiled shared libraries (like .so on Linux, .dll on Windows, or .dylib on macOS).

A Simple C Example πŸ’»

Let's say we have a simple C file, math_ops.c.

C Code (math_ops.c):

c
// A simple function to add two numbers
double add_doubles(double x, double y) {
    return x + y;
}

First, we need to compile this into a shared library. On Linux or macOS, you can do this with:

bash
gcc -shared -fPIC -o libmath.so math_ops.c

Now we have libmath.so in the same directory. Let's call it from Julia!

Julia Code:

julia
# The syntax for ccall is:
# ccall((:function_name, "library_path"), ReturnType, (ArgType1, ArgType2, ...), arg1, arg2, ...)

# Let's call our 'add_doubles' function
# :add_doubles is the function name in the C code
# "./libmath.so" is the path to our shared library
# Cdouble is the Julia type corresponding to a C 'double'
result = ccall((:add_doubles, "./libmath.so"), Cdouble, (Cdouble, Cdouble), 2.5, 3.5)

println("The result from our C function is: ", result)
# Output: The result from our C function is: 6.0

Breaking down the ccall syntax:

  • (:function_name, "library_path"): A tuple containing the function's symbol in the library and the path to the library file.
  • ReturnType: The Julia type that corresponds to the return type of the C/Fortran function (e.g., Cdouble, Cint, Cvoid for no return).
  • (ArgType1, ...): A tuple of Julia types that correspond to the C/Fortran function's argument types.
  • arg1, ...: The actual values you are passing to the function.

Fun Fact: You're already using ccall all the time without knowing it! A huge portion of Julia's standard library, including its powerful linear algebra functions, uses ccall under the hood to call highly optimized C and Fortran libraries like OpenBLAS and LAPACK.

Important Note: Using ccall is like working with a powerful tool. It's incredibly fast, but you're now responsible for getting the types exactly right. If the C function expects a float and you pass it a double, you might get unexpected results or even a crash. Always have the C/Fortran function's documentation handy!


πŸ“Š 3. Running R Code with RCall.jl

R is the undisputed king of classical statistics and data visualization, thanks to its massive repository of packages (CRAN) and the legendary ggplot2.

The Problem: Your team's lead statistician, "R-yan," has built a sophisticated statistical model in R. You need to run this model on data you've prepared in Julia and then use his ggplot2 script to generate a publication-quality chart.

The Solution: RCall.jl is to R what PythonCall.jl is to Python. It provides a seamless bridge to the R interpreter.

Getting Started πŸ“ˆ

Just like PythonCall.jl, this is a standard package. Enter the package manager with ] and type:

julia
(v1.10) pkg> add RCall

RCall.jl will then try to find your R installation.

A Simple R Example 🎨

RCall.jl gives you a very cool R"" string macro. Anything you write inside this macro is executed by R. You can even pass Julia variables into the R code using $ interpolation.

Let's generate some data in Julia and plot it with ggplot2 in R.

Julia Code:

julia
using RCall, DataFrames

# 1. Create some data in a Julia DataFrame
julia_df = DataFrame(
    Category = repeat(["A", "B", "C"], inner=4),
    Value = randn(12) .+ [0, 2, -1.5]' # Add offsets to make them distinct
)

# 2. Send our Julia DataFrame over to R's environment.
# The '$' interpolates the Julia variable 'julia_df' into the R code.
R"""
# First, ensure ggplot2 is installed and loaded in R
if (!requireNamespace("ggplot2", quietly = TRUE)) {
  install.packages("ggplot2", repos = "http://cran.us.r-project.org")
}
library(ggplot2)

# R now has a data.frame named 'julia_df'
# Let's create a plot with it
my_plot <- ggplot(julia_df, aes(x=Category, y=Value, fill=Category)) +
           geom_boxplot() +
           ggtitle("Plot Generated in R from Julia Data!") +
           theme_minimal()

# Save the plot to a file
ggsave("julia_to_r_plot.png", my_plot)
"""

println("Plot saved to julia_to_r_plot.png!")

When you run this, RCall.jl will:

  1. Start an R session.
  2. Intelligently convert your Julia DataFrame into an R data.frame.
  3. Execute the R script within the R"" macro.
  4. R will then generate and save the plot.

This is incredibly powerful! You get to do all your high-performance data manipulation in Julia and then hand it off to R for its world-class statistical and plotting capabilities, all in one script.


Conclusion

You've just learned one of Julia's most powerful features. Interoperability isn't just a technical detail; it's a philosophy. It means you don't have to reinvent the wheel. You can stand on the shoulders of giants and use the best tool for the job, regardless of the language it was written in.

  • Need to tap into the massive Python data science ecosystem? PythonCall.jl is your answer.
  • Need to call a lightning-fast, low-level C or Fortran library? ccall is built right into the language for you.
  • Need to leverage sophisticated statistical models or ggplot2 from R? RCall.jl has you covered.

By mastering these tools, you transform from being just a Julia programmer into a polyglot programmer who can orchestrate complex projects and leverage the strengths of the entire programming world. Happy coding! 🌐

πŸ“š Further Reading & References

Challenge

You are a Julia developer tasked with integrating code from Python, C, and R to perform a series of calculations. Your goal is to write the necessary Julia code to call functions from each of these languages and store the results in specified Julia variables.

Task 1: Python Integration with PythonCall.jl

  1. Import the Python numpy module, giving it the alias np.
  2. You are given a Julia variable py_input = [4.0, 16.0, 36.0].
  3. Use the numpy.sqrt function to compute the square root of each element in py_input.
  4. The result from Python will be a Python object. Explicitly convert this object to a Vector{Float64} and assign it to the Julia variable julia_from_py.

Task 2: C Library Integration with ccall

  1. Call a high-performance C function named compute_area which is located in a hypothetical shared library named "libgeometry.so".
  2. This C function takes two C double arguments representing the width and height of a rectangle and returns their product as a C double.
  3. Call the function with a width of 10.5 and a height of 4.0.
  4. Assign the returned value to the Julia variable julia_from_c.

Task 3: R Statistics Integration with RCall.jl

  1. You have a Julia variable r_input = [5, 10, 15, 20, 25].
  2. Use the R"" string macro to execute R code from within Julia.
  3. Your R code must calculate the standard deviation of the r_input data using R's native sd() function.
  4. Assign the result directly to the Julia variable julia_from_r.

Expected result

The completed code must correctly implement all three interoperability tasks by defining the variables julia_from_py, julia_from_c, and julia_from_r.

  • Task 1: The solution must first import numpy using const np = pyimport("numpy"). Then, julia_from_py should be assigned the result of calling np.sqrt with py_input and converting the returned Python object using pyconvert(Vector{Float64}, python_result).

  • Task 2: julia_from_c must be assigned the result of a ccall. The ccall must correctly specify the function and library tuple (:compute_area, "libgeometry.so"), the return type Cdouble, the argument types tuple (Cdouble, Cdouble), and the actual arguments 10.5 and 4.0.

  • Task 3: julia_from_r must be assigned the output of the R"" macro. The string inside the macro must contain the expression sd($r_input) to correctly interpolate the Julia variable into the R code.

julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.