numpy / numpy/numpy

BUG: f2py does not correctly handle double complex type when using iso_fortran_env kinds

Open
#30,352 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

00 - Bug component: numpy.f2py
Dominant language
Python
Stars
32.8k
Forks
12.8k
Avg merge
1d 7h
Merged PRs (30d)
197

Description

Describe the issue:

When declaring a double complex variable in a Fortran program using either iso_c_binding or iso_fortran_env to handle its kind, i.e. complex(kind=dp), f2py maps it to a single precision complex C
variable typedef struct {float r,i;} complex_float; instead of the expected double precision. This yields a segfault of the program. This is working fine when the variable is declared in the old-fashioned format complex(kind=8) .
Here is a quick reproducer:

module test

   use iso_fortran_env, only: dp=>real64

   implicit none

contains

   subroutine test_function(arr, nt)

      integer :: nt
      ! complex(kind=8), intent(inout) :: arr(nt) ! This is OK but not standard
      complex(kind=dp), intent(inout) :: arr(nt) ! This is segfaulting
                                                 ! C file declares it as a 
                                                 ! typedef struct {float r,i;} complex_float;

      arr(:) = (1.0_dp,-1.0_dp)

   end subroutine test_function

end module test

and the associated python function

from test import *
import numpy as np

x = np.zeros((10), np.complex128)
test.test_function(x)
print(x)
Reproduce the code example:
from test import *
import numpy as np

x = np.zeros((10), np.complex128)
test.test_function(x)
print(x)
Error message:

Python and NumPy Versions:

2.2.2
3.13.5 (main, Aug 19 2025, 14:39:27) [GCC]

Runtime Environment:

No response

Context for the issue:

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at f2py's Fortran type-mapping entry point and reproduce the issue with the provided module using complex(kind=dp), comparing it with complex(kind=8). Done means the generated C representation preserves double precision and the Python reproducer completes without a segmentation fault.

Written by the indexing model from the issue text.

Assessment

Tech stack
fortran, python
Domain
compilers, tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.