Computational Science Community Wiki

University of Manchester GPU FAQ - Calling OpenCL and CUDA from Fortran


alt="NVIDIA CUDA Research Centre"

  • Software for GPUs inc. compiler/directives, maths libs & tools (debuggers and profilers)


1. Introduction

No native fortran OpenCL library exists and so to call OpenCL from a fortran code one solution is to write an intermediate C layer. The fortran code calls the C functions which in turn call the OpenCL code. How much OpenCL you expose to the fortran code is up to you. For example, you may want to return device memory objects to the fortran code for use in other routines (such as copying data to and from the device, kernels calls etc.) but you may want to hide the lower level objects such as the OpenCL context, kernels etc.

CUDA does have a fortran interface to the CUBLAS library. However, it may still be useful to wrap some of the lower level CUDA functions (such as those used to allocate device memory and transfer data to/from the device) within a C layer that can then be called from fortran.

The code below shows a skeleton fortran program that calls C functions. A few points to note are:

2. Download

The C code discussed below can be downloaded as opencl_funcs.c and cuda_funcs.cu. You should modify any kernel code examples to suit your own problem.

3. Fortran Code

4. C code

The C code exposes some of the details to fortran (return device memory object as pointers) but hides the OpenCL device, platform, kernel etc. This isn't a general intermediate layer in that it only supports one device, kernel and command queue. It also uses a function (run_kernel) that is specific to the kernel (in terms of args that are passed to the kernel, global and local work sizes. It would be possible to generalise this.

Note: The skeleton code below does not implement all of the functions declared in the fortran code. Error flags from OpenCL functions are not always tested - you should do this. Also, the opencl_init() function is a very basic example of initialising the OpenCL device. You may want to test for specific devices and properties in real code.

5. Other Projects

Other external projects listed here are also providing Fortran / OpenCL interoperability