Created
June 16, 2020 03:33
-
-
Save angus-g/b925effb9c8961167665934a6b3f915c to your computer and use it in GitHub Desktop.
C/Fortran memory interop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
void allocate_from_c(double **arr, int *n) { | |
*arr = (double*)malloc(5 * sizeof(double)); | |
*n = 5; | |
double *x = *arr; | |
for (int i = 0; i < *n; i++) { | |
x[i] = (double)i; | |
} | |
printf("from c: %p\n", *arr); | |
} | |
void deallocate_from_c(double **arr) { | |
free((void*)*arr); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
program read_carray | |
use iso_c_binding | |
implicit none | |
interface allocate_from_c | |
subroutine allocate_from_c(arr, n) bind(c) | |
use iso_c_binding | |
type(c_ptr), intent(out) :: arr | |
integer(c_int), intent(out) :: n | |
end subroutine allocate_from_c | |
end interface allocate_from_c | |
interface deallocate_from_c | |
subroutine deallocate_from_c(arr) bind(c) | |
use iso_c_binding | |
type(c_ptr), intent(in) :: arr | |
end subroutine deallocate_from_c | |
end interface deallocate_from_c | |
type(c_ptr) :: arr | |
integer :: n | |
double precision, dimension(:), pointer :: darr | |
print *, "Hello world" | |
call allocate_from_c(arr, n) | |
print *, "Allocated array length", n | |
print *, arr | |
call c_f_pointer(arr, darr, [n]) | |
print *, darr | |
call deallocate_from_c(arr) | |
end program read_carray |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment