# Allocate interoperability and C descriptors

**URL:** <https://fortran-lang.discourse.group/t/allocate-interoperability-and-c-descriptors/5088>\
**Category:** Help\
**Created:** [January 26, 2023, 5:04pm UTC](https://fortran-lang.discourse.group/t/allocate-interoperability-and-c-descriptors/5088 "2023-01-26T17:04:01Z")\
**Posts on this page:** 9\
**Page:** 2

<div class="post-metadata">

**Author:** ![ivanpribec](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/ivanpribec/32/3290_2.png) [@ivanpribec](https://fortran-lang.discourse.group/u/ivanpribec)\
**Post date:** [January 27, 2023, 8:43pm UTC](https://fortran-lang.discourse.group/t/allocate-interoperability-and-c-descriptors/5088/21 "2023-01-27T20:43:47Z")

</div>

> [@PierU](#):
>
> But I didn’t get that in some cases it would be possible to allocate on the Fortran side before loading/generating the data on the C side (so no data duplication is needed), as you show here.

I’ve been confused in the past with wrappers (like in this [StackOverflow thread](https://stackoverflow.com/a/73861031/4283055)). Typically you find examples of wrapping non-interoperable C/C++ objects in Fortran rather than the other way round. I guess not that many C/C++ developers appreciate the features of modern Fortran.

Btw, in case you are willing to use C++, the C API can be wrapped in a C++ class which has the benefit of automatic lifetime management (RAII) and other C++ goodies like `std::span` and the STL:

```cpp
#include <numeric>
#include <span>

#include "somemodule_wrap.h"

class Sometype {
public:

    // Constructor
    Sometype(int n) : ptr{ sometype_create(n) } {}

    // Destructor
    ~Sometype() { sometype_free(ptr); }

    // Access array member `a`
    std::span<double> a() const {
        int n; double *a;
        a = static_cast<double *>( sometype_a(ptr,&n) );
        return { a, (size_t) n };
    }

    // Retrieve raw pointer to underlying object
    void *get() const { return ptr; }

private:
    void *ptr{nullptr};
};

void frout(const Sometype& x) {
    frout2_wrap( x.get() );
}

```

The usage becomes simpler than in C and you get to use STL algorithms with the `std::span`

```auto
int main(void) 
{
    Sometype x{6};
    
    auto a = x.a(); // a is a view (memory owned by x)

    // Fill with increasing numbers
    std::iota(a.begin(),a.end(),0.0);
    
    frout(x);

    return 0;
}

```

---

<div class="post-metadata">

**Author:** ![mEm](https://avatars.discourse-cdn.com/v4/letter/m/90ced4/32.png) [@mEm](https://fortran-lang.discourse.group/u/mEm)\
**Post date:** [January 16, 2025, 11:25am UTC](https://fortran-lang.discourse.group/t/allocate-interoperability-and-c-descriptors/5088/22 "2025-01-16T11:25:11Z")

</div>

I don’t know whether I should have opened a new thread or maybe this one is close enough to my question.  
I need to possibly allocate and modify C pointers from within Fortran, possibly without needing to force the C side to use `ISO_Fortran_binding.h`.  
Consider the following:

```fortran
! modify.f90
subroutine modify(ptrptr) bind(c)
   use, intrinsic :: iso_c_binding
   implicit none
   type(c_ptr), value :: ptrptr
   type(c_ptr), pointer :: ptr
   real(8), pointer :: value_ptr
   real(8), allocatable, target :: val

   call c_f_pointer(ptrptr, ptr)
   call c_f_pointer(ptr, value_ptr)
   if (.not. associated(value_ptr)) then
      print *, " C ptr is NULL"
    
      ! Create new memory
      allocate(val)
      ptr = c_loc(val)
      call c_f_pointer(ptr, value_ptr)

      ! Here I need to do like *ptrptr = ptr
      ! if I want to propagate changes to the outside world.
   endif
   value_ptr = 120.
end subroutine

```

```c
// main.c
#include <stdio.h>

extern void modify(double **);

int main(void)
{
   double value = 0.;
   double *vaddr = &value;
   modify(&vaddr);
   printf("%12.5f\n", value);

   double *v = NULL;
   modify(&v);
   if (v)
      printf("%12.5f\n", *v);
   return 0;
}

```

First, is this code standard conforming? I have doubts about the second case…  
Also because, I cannot understand why for this second case, which is the reason why I am reopening this thread, the memory seems to be actually allocated, but not modified.  
That does not look good to me, which flags that something is not working properly.

**EDIT** : it would be nice to have, on the Fortran side, the companion `f_c_pointer(fobj, cptr)` subroutine, to assign the c-address of a Fortran entity to the pointed address of a `type(c_ptr)` Fortran object.

**EDIT2** : thinking about it, I just realise that in fact, mixed C-Fortran allocations are not really interoperable if not done via the ISO Binding API. So, what I am trying to achieve **requires** using `ISO_Fortran_binding.h`. Full stop. Sorry for bringing this one up again.

---

<div class="post-metadata">

**Author:** ![Euler-37](https://avatars.discourse-cdn.com/v4/letter/e/b19c9b/32.png) [@Euler-37](https://fortran-lang.discourse.group/u/Euler-37)\
**Post date:** [January 16, 2025, 12:23pm UTC](https://fortran-lang.discourse.group/t/allocate-interoperability-and-c-descriptors/5088/23 "2025-01-16T12:23:09Z")

</div>

```auto
! modify.f90
subroutine modify(ptrptr) bind(c)
   use, intrinsic :: iso_c_binding
   implicit none
   type(c_ptr), intent(inout) :: ptrptr
   real(8), pointer :: value_ptr
   call c_f_pointer(ptrptr, value_ptr)
   if (.not. associated(value_ptr)) then
      print *, " C ptr is NULL"
    
      ! Create new memory
      allocate(value_ptr)
      ptrptr= c_loc(value_ptr)
   endif
   value_ptr = 120.
end subroutine

```

variable with `allocatable` attribute will auto-deallocate when it leave subroutine,so it must have `pointer` attribute.

and may it is more clear if use `c_associated`

```auto
! modify.f90
subroutine modify(ptrptr) bind(c)
   use, intrinsic :: iso_c_binding
   implicit none
   type(c_ptr), intent(inout) :: ptrptr
   real(8), pointer :: value_ptr
   if (c_associated(ptrptr)) then
      call c_f_pointer(ptrptr, value_ptr)
   else   
      print *, " C ptr is NULL"
      ! Create new memory
      allocate(value_ptr)
      ptrptr= c_loc(value_ptr)
   endif
   value_ptr = 120.
end subroutine

```

---

<div class="post-metadata">

**Author:** ![mEm](https://avatars.discourse-cdn.com/v4/letter/m/90ced4/32.png) [@mEm](https://fortran-lang.discourse.group/u/mEm)\
**Post date:** [January 16, 2025, 1:13pm UTC](https://fortran-lang.discourse.group/t/allocate-interoperability-and-c-descriptors/5088/24 "2025-01-16T13:13:13Z")

</div>

> [@Euler-37](#):
>
> variable with `allocatable` attribute will auto-deallocate when it leave subroutine,so it must have `pointer` attribute.

My world, this made me realise I have been away from Fortran too much that I completely overlooked this one. Thanks for your answer 🙂

---

<div class="post-metadata">

**Author:** ![PierU](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/pieru/32/1848_2.png) [@PierU](https://fortran-lang.discourse.group/u/PierU)\
**Post date:** [January 16, 2025, 3:29pm UTC](https://fortran-lang.discourse.group/t/allocate-interoperability-and-c-descriptors/5088/25 "2025-01-16T15:29:05Z")

</div>

I don’t get why you need the `ptr` intermediate pointer and `val`… Isn’t it OK like this?

```auto
! modify.f90
subroutine modify(ptrptr) bind(c)
   use, intrinsic :: iso_c_binding
   implicit none
   type(c_ptr), intent(inout) :: ptrptr
   real(8), pointer :: value_ptr

   if (c_associated(ptrptr)) 
      call c_f_pointer(ptrptr, value_ptr)
   else
      print *, " C ptr is NULL"
      ! Create new memory
      allocate( value_ptr )
      ptrptr = c_loc(value_ptr )
   endif
   value_ptr = 120.
end subroutine

```

> [@mEm](#):
>
> **EDIT** : it would be nice to have, on the Fortran side, the companion `f_c_pointer(fobj, cptr)` subroutine, to assign the c-address of a Fortran entity to the pointed address of a `type(c_ptr)` Fortran object.

Isn’t it `c_loc()` ?

---

<div class="post-metadata">

**Author:** ![PierU](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/pieru/32/1848_2.png) [@PierU](https://fortran-lang.discourse.group/u/PierU)\
**Post date:** [January 16, 2025, 3:30pm UTC](https://fortran-lang.discourse.group/t/allocate-interoperability-and-c-descriptors/5088/26 "2025-01-16T15:30:01Z")

</div>

> [@mEm](#):
>
> **EDIT2** : thinking about it, I just realise that in fact, mixed C-Fortran allocations are not really interoperable if not done via the ISO Binding API.

I think it’s OK as long as you allocate/deallocate on the same side.

---

<div class="post-metadata">

**Author:** ![RonShepard](https://avatars.discourse-cdn.com/v4/letter/r/a3d4f5/32.png) [@RonShepard](https://fortran-lang.discourse.group/u/RonShepard)\
**Post date:** [January 16, 2025, 6:58pm UTC](https://fortran-lang.discourse.group/t/allocate-interoperability-and-c-descriptors/5088/27 "2025-01-16T18:58:29Z")

</div>

> [@mEm](#):
>
> **EDIT** : it would be nice to have, on the Fortran side, the companion `f_c_pointer(fobj, cptr)` subroutine, to assign the c-address of a Fortran entity to the pointed address of a `type(c_ptr)` Fortran object.

The `c_loc()` intrinsic does this on the fortran side. On the C side, passing an array or a scalar object without the `value` attribute in the interface results in a normal C pointer as the argument.

---

<div class="post-metadata">

**Author:** ![mEm](https://avatars.discourse-cdn.com/v4/letter/m/90ced4/32.png) [@mEm](https://fortran-lang.discourse.group/u/mEm)\
**Post date:** [January 16, 2025, 7:02pm UTC](https://fortran-lang.discourse.group/t/allocate-interoperability-and-c-descriptors/5088/28 "2025-01-16T19:02:12Z")

</div>

Yeah, missed to realise this until @Euler-37 as well as yourself provided these examples. I guess my mistake was to pass the `type(c_ptr)` with `value` attribute. I thought too much in C-style while using Fortran.

---

<div class="post-metadata">

**Author:** ![mEm](https://avatars.discourse-cdn.com/v4/letter/m/90ced4/32.png) [@mEm](https://fortran-lang.discourse.group/u/mEm)\
**Post date:** [January 16, 2025, 7:04pm UTC](https://fortran-lang.discourse.group/t/allocate-interoperability-and-c-descriptors/5088/29 "2025-01-16T19:04:44Z")

</div>

Indeed.

[Previous page](https://fortran-lang.discourse.group/t/allocate-interoperability-and-c-descriptors/5088.md?page=1)
