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
相关推荐
揽星河..42 分钟前
【C语言】分支和循环
c语言·c++·算法
小熊恋旧43 分钟前
Python 面向对象编程:方法、属性、继承与多态详解
开发语言·python
云边云科技_云网融合44 分钟前
面向汽车零部件制造业场景的解决方案 | 70 秒:一台车下线的时间里,藏着五张网
开发语言·汽车·php
Evand J1 小时前
【PMSM滤波例程2】PMSM未知负载转矩观测EKF。MATLAB例程(负载增广EKF与实际仿真结果)。附下载链接
开发语言·matlab·电机
will_net1 小时前
apollo 站点部署&C#接入
开发语言·c#·apollo
晗夜未央2 小时前
任务队列反复失败,先分清重试、阻塞和结果待核对
开发语言·javascript
熊猫钓鱼>_>2 小时前
四种书签,一条时间线:一个读书 App 的记忆颗粒与它的边界案例【鸿蒙心迹】
开发语言·华为·ai编程·harmonyos·鸿蒙·openharmony·鸿蒙pc
努力努力再努力wz2 小时前
【Lua 入门系列】Lua 函数深入理解:函数对象、多返回值、可变参数、闭包、递归与尾调用优化
开发语言·lua
揽星河..3 小时前
【C语言】猜数字游戏
c语言·算法·游戏
飞浪纪元[FWC–FE]3 小时前
从零到一键绿:Qt 5.14.2 + VS2019 开发环境搭建、Kit 套件配置与构建错误修复完全手册
开发语言·qt