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
相关推荐
Re.不晚14 小时前
Java入门17——异常
java·开发语言
精彩极了吧15 小时前
C语言基本语法-自定义类型:结构体&联合体&枚举
c语言·开发语言·枚举·结构体·内存对齐·位段·联合
南极星100516 小时前
蓝桥杯JAVA--启蒙之路(十)class版本 模块
java·开发语言
baidu_2474386116 小时前
Android ViewModel定时任务
android·开发语言·javascript
Dev7z16 小时前
基于 MATLAB 的铣削切削力建模与仿真
开发语言·matlab
不能隔夜的咖喱16 小时前
牛客网刷题(2)
java·开发语言·算法
小天源16 小时前
Error 1053 Error 1067 服务“启动后立即停止” Java / Python 程序无法后台运行 windows nssm注册器下载与报错处理
开发语言·windows·python·nssm·error 1053·error 1067
进击的小头16 小时前
实战案例:51单片机低功耗场景下的简易滤波实现
c语言·单片机·算法·51单片机
肉包_51117 小时前
两个数据库互锁,用全局变量互锁会偶发软件卡死
开发语言·数据库·c++
大空大地202617 小时前
流程控制语句--if语句
开发语言