This behavior is not safe, as dolfinx.fem.Function(..).vector
does provide a view into data stored in the dolfinx.fem.Function(Vh)
. This data (and the underlying vector) is deleted when dl.fem.Functon(Vh)
goes out of scope, which is right away. (This is due to PETSc’s modern garbage collection (https://github.com/FEniCS/dolfinx/blob/main/python/dolfinx/fem/function.py#L288-L290, garbage collection different between petsc4py 3.17.4 and 3.18.3 (#1309) · Issues · PETSc / petsc · GitLab).
Thus, if you want to use the petsc-vector
generated by a dolfinx.fem.Function
, you need to do it in two steps:
u = dl.fem.Function(Vh)
uvec = u.vector
If you just want a petsc-vector (not wrapped as a DOLFINx function), you can use:
dolfinx.la.create_petsc_vector(Vh.dofmap.index_map, Vh.dofmap.index_map_bs)