chapter eleven

11 Interoperability with C: Exposing your app to the web

 

This chapter covers:

  • Why invoke C code from Fortran?
  • Interfacing C built-in types, structs, and functions from Fortran
  • Writing a minimal Fortran TCP client and server

Pure Fortran is powerful for numerical and array-oriented computation that is ubiquitous in physical sciences and engineering. Howewer, there are quite a few things that aren’t possible in Fortran alone, but can be done in a low-level systems programming language such as C. These include reading and writing data to hardware devices, drawing graphics on the screen in real-time, or sending data over the internet. Interoperability with C allows a programmer to call C functions from Fortran programs. This is important for two reasons: First, enables the above-mentioned low-level functionality, and gives Fortran access to the C ecosystem of libraries. Second, C itself is easily called from many popular programming languages today, such as Python, JavaScript, Go, or Rust. By using C as the interfacing language, Fortran code can be invoked from most other languages. In the real world, this allows Fortran code to be used within web servers, databases, and real-time graphics.

11.1  Interfacing C: Writing a minimal TCP client and server

11.1.1  Introducing networking to Fortran

11.1.2  Installing libdill

11.2  TCP server program: Receiving network connections

11.2.1  IP address data structures

11.2.2  Initializing the IP address structure

11.2.3  Checking IP address values

11.2.4  Intermezzo: Matching compatible C and Fortran data types

11.2.5  Creating a socket and listening for connections

11.2.6  Accepting incoming connections to a socket

11.2.7  Sending a TCP message to the client

11.2.8  Closing a connection

11.3  TCP client program: Connecting to a remote server

11.3.1  Connecting to a remote socket

11.3.2  Receiving a message

11.3.3  The complete client program

11.4  Some interesting mixed Fortran-C projects

11.5  Answer Key

11.5.1  Exercise 1: The Fortran interface to ipaddr_port