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:
(v1.10) pkg> add PythonCallNow, 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):
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:
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)
endWhat's happening here?
pyimport("module_name")is your gateway. It loads a Python module and gives you back a specialPyObjectthat acts as a remote control for the real Python object.- You can call methods and access attributes on this
PyObjectusing the familiar dot syntax (e.g.,re.findall). - Data types are often converted automatically. Julia strings become Python strings, numbers become numbers, etc.
- 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. - Zero-Copy Magic: For big data like large numerical arrays,
PythonCall.jlis 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.jlstarts and maintains a Python interpreter session inside the Julia process. When youpyimportor 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):
// 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:
gcc -shared -fPIC -o libmath.so math_ops.cNow we have libmath.so in the same directory. Let's call it from Julia!
Julia Code:
# 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.0Breaking 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,Cvoidfor 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
ccallall the time without knowing it! A huge portion of Julia's standard library, including its powerful linear algebra functions, usesccallunder 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:
(v1.10) pkg> add RCallRCall.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:
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:
- Start an R session.
- Intelligently convert your Julia
DataFrameinto an Rdata.frame. - Execute the R script within the
R""macro. - 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.jlis your answer. - Need to call a lightning-fast, low-level C or Fortran library?
ccallis built right into the language for you. - Need to leverage sophisticated statistical models or
ggplot2from R?RCall.jlhas 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
- PythonCall.jl:
- Official Documentation: https://juliapy.github.io/PythonCall.jl/stable/
- GitHub Repository: https://github.com/JuliaPy/PythonCall.jl
- Calling C and Fortran (
ccall):- Official Julia Documentation on Calling C: https://docs.julialang.org/en/v1/manual/calling-c-and-fortran-code/
- RCall.jl:
- Official Documentation: https://juliainterop.github.io/RCall.jl/stable/
- GitHub Repository: https://github.com/JuliaInterop/RCall.jl
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
- Import the Python
numpymodule, giving it the aliasnp. - You are given a Julia variable
py_input = [4.0, 16.0, 36.0]. - Use the
numpy.sqrtfunction to compute the square root of each element inpy_input. - The result from Python will be a Python object. Explicitly convert this object to a
Vector{Float64}and assign it to the Julia variablejulia_from_py.
Task 2: C Library Integration with ccall
- Call a high-performance C function named
compute_areawhich is located in a hypothetical shared library named"libgeometry.so". - This C function takes two C
doublearguments representing thewidthandheightof a rectangle and returns their product as a Cdouble. - Call the function with a width of
10.5and a height of4.0. - Assign the returned value to the Julia variable
julia_from_c.
Task 3: R Statistics Integration with RCall.jl
- You have a Julia variable
r_input = [5, 10, 15, 20, 25]. - Use the
R""string macro to execute R code from within Julia. - Your R code must calculate the standard deviation of the
r_inputdata using R's nativesd()function. - 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
numpyusingconst np = pyimport("numpy"). Then,julia_from_pyshould be assigned the result of callingnp.sqrtwithpy_inputand converting the returned Python object usingpyconvert(Vector{Float64}, python_result).Task 2:
julia_from_cmust be assigned the result of accall. Theccallmust correctly specify the function and library tuple(:compute_area, "libgeometry.so"), the return typeCdouble, the argument types tuple(Cdouble, Cdouble), and the actual arguments10.5and4.0.Task 3:
julia_from_rmust be assigned the output of theR""macro. The string inside the macro must contain the expressionsd($r_input)to correctly interpolate the Julia variable into the R code.