Introduction to the Julia programming language

21 Integrating Python, C, and, FORTRAN¶

Python (1)¶

Examples from this notebook.

In [ ]:
using PyCall
In [ ]:
# Get Python version information
PyCall.pyversion
In [ ]:
math = pyimport("math")
math.sin(math.pi / 4) # returns ≈ 1/√2 = 0.70710678...

Python (2)¶

You can also write your own Python code as follows:

In [ ]:
x = [-0.6, -0.2, 0.2, 0.6]
y = [5., 3., 5., 8.]

py"""
import numpy as np
def corrcoef_numpy(xvals,yvals):
    return np.corrcoef(xvals,yvals)[0][1]
"""

corrcoef_numpy = py"corrcoef_numpy"
println("correlation coefficient: $(corrcoef_numpy(x,y))")

C¶

One can use the @ccall macro:

@ccall library.function_name(argvalue1::argtype1, ...)::returntype

Here is an example:

#include <stdio.h>

void say_y(int y) {
    printf("Hello from C: got y = %d.\n", y);
}

Create a shared library. My command (on a MacBook Air M2): gcc -shared -o mylib.dylib -fPIC mylib.c

In [5]:
@ccall "./misc/mylib.dylib".say_y(5::Cint)::Cvoid
Hello from C: got y = 5.

C++¶

For using C++ libraries, we use 'CxxWrap'. Here is the example from the CxxWrap documentation:

hello.cpp in directory hello:

#include <string>

#include "jlcxx/jlcxx.hpp"

std::string greet() {
   return "hello, world";
}

JLCXX_MODULE define_julia_module(jlcxx::Module& mod) {
  mod.method("greet", &greet, "documentation for greet");
}

It is convenient to use cmake. Here is CMakeLists.txt:

project(hello)

cmake_minimum_required(VERSION 3.5)
set(CMAKE_MACOSX_RPATH 1)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib")

find_package(JlCxx)
get_target_property(JlCxx_location JlCxx::cxxwrap_julia LOCATION)
get_filename_component(JlCxx_location ${JlCxx_location} DIRECTORY)
set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib;${JlCxx_location}")

message(STATUS "Found JlCxx at ${JlCxx_location}")

add_library(hello SHARED hello.cpp)

target_link_libraries(hello JlCxx::cxxwrap_julia)

install(TARGETS
  hello
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
RUNTIME DESTINATION lib)
In [1]:
module CppHello
  using CxxWrap
  @wrapmodule(() -> joinpath("./misc/build/lib","libhello"))

  function __init__()
    @initcxx
  end
end
Main.CppHello
In [4]:
CppHello.greet()
"hello, world"