fortran access pointer returned from c

a.f90

bash 复制代码
program main
        use iso_c_binding
        implicit none
        type(c_ptr) :: ADD1
        integer R
        integer(C_INT), pointer :: S(:)  ! Declare a Fortran pointer for the array
        type(c_ptr) :: c_ptr1
        external ADD1
        integer :: i

        R = 8
        c_ptr1 = ADD1( R )

        call c_f_pointer(c_ptr1, S, [10])  ! Assume the size is 10
        print *, 'Array from C function: '
        do i = 1, 10
        print *, S(i)
        end do
end program

b.c

bash 复制代码
# include <stdlib.h>
# include <stdio.h>

int* add1_( pf )
        int *pf;
{

        printf("%d\n",*pf);
        int n = 10; // size of the array
        int *arr = (int *)malloc(n * sizeof(int)); // allocate memory for n integers

        // Check if memory allocation was successful
        if (arr == NULL) {
                printf("Memory allocation failed\n");
                return NULL; // Return error code
        }
        // Initialize and print the array
        for (int i = 0; i < n; i++) {
                arr[i] = i * i; // Assign some values
                printf("%d ", arr[i]); // Print each element
        }
        printf("\n");
        return (int *) arr;
}

Makefile

bash 复制代码
all:
        gcc -c b.c
        gfortran a.f90 b.o -o a.out
相关推荐
91刘仁德2 小时前
C++ 继承和多态 设计模式
c语言·c++·笔记
码行山野赴时序归途2 小时前
链表家族收官篇:循环链表
c语言·开发语言·数据结构·链表
景熙55232 小时前
单体项目编写思路和落地形式
java·开发语言
库玛西3 小时前
哈夫曼树与前缀编码:数据压缩的贪心核心
c语言·c++·笔记·考研
计算机毕设定制辅导-无忧学长3 小时前
《基于SpringBoot的未成年人健康知识科普平台的设计与实现》
java·开发语言·vue.js·spring boot·未成年人健康知识科普平台
Ivanqhz3 小时前
Ping-Pong 双缓冲
开发语言·人工智能·python·深度学习·mlir
m0_734571763 小时前
深入理解C++ RAII
开发语言·c++
泡海椒3 小时前
jquick-pdf 表格实战:动态数据 PDF 报表生成
java·开发语言·pdf
雷✘4 小时前
C 语言预处理中的宏展开、条件编译与头文件保护
c语言
aramae4 小时前
模拟实现memset()(C语言)
c语言·开发语言·后端