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
相关推荐
xurileidian1 小时前
第 22 篇 · 边玩边学Python · 双等号与 is 不是一回事
开发语言·python·spring
FRing031 小时前
for循环、while循环、Java高级语法、数组
java·开发语言·后端·算法
syf0611131 小时前
Java Math 类详解:常用数学运算方法全解析
java·开发语言
是main不是漫2 小时前
【双指针 | LeetCode11 盛最多水的容器】O(n²) 超时,O(n) 封神:这道“装水题“只差一个思路
开发语言·数据结构·c++·算法
老花眼猫2 小时前
C语言绘图方法:(24)鼓形缩放旋转
c语言·经验分享·青少年编程·课程设计
慧都产品智能化2 小时前
汽车软件年底自查:按安全影响排定缺陷整改顺序
c语言·c++·测试工具·单元测试·汽车·代码规范
geovindu3 小时前
python: Gradient Boosting
开发语言·后端·python·算法·boosting
Zwawa3 小时前
USB 与有线接口:插上去之后,这条线上发生了什么
c语言·单片机·嵌入式
星夜离尘564 小时前
MATLAB:两路读数平均相差 8 mV,换位能分出传感器偏差和通道偏差吗?
开发语言·matlab
时间的情敌4 小时前
Three.js 水位模拟、水体 Shader、罐体液位动态变化(水箱、水池、储罐液位)
开发语言·javascript·three.js