Skip to content

[FEAT]  #2787

@omaxian

Description

@omaxian

Is there a way to link fortran to C++ to python with pybind11?

Here is a simple example of what I mean. Suppose I have the following fortran module

! fortmodule.f90
module fortmodule
use iso_c_binding
implicit none

integer(C_INT), bind(C), dimension(5) :: numbers

contains

subroutine fortransub() bind(C)

   print *, "Hello from Fortran!"
   numbers(1) = 1
   numbers(2) = 2
   numbers(3) = 3
   numbers(4) = 4
   numbers(5) = 5

end subroutine

end module

And I wanted to link it with pybind11 doing something like:

// TestFortran.cpp
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <stdio.h>

extern "C" void fortransub();
extern "C" int numbers[5];

int makeMe()
{
   int i;
   printf("Hello from C!\n");
   fortransub();
   for (i=0; i<5; i=i+1)
      printf("%d ", numbers[i]);
   printf("\n");

return 0;
}


PYBIND11_MODULE(TestFortran, m) {
    
    m.def("makeMe", &makeMe, "Test fortran/C/python");
}

Is something like this possible? I am not sure how to compile if it is.

If it were pure C++ (i.e., if MakeMe were replaced with main) the compile statement would simply be:

g++ -c TestFortran.cpp
gfortran TestFortran.o fortmodule.f90

Is there a way to adapt this to pybind11? Thank you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions