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
相关推荐
维吉斯蔡5 小时前
【VS Code / Cursor】文件夹右键快捷打开与文件类型自动关联
开发语言·程序人生·学习方法
luj_17688 小时前
星火科技助力边远地区防病攻坚
c语言·开发语言·c++·经验分享·算法
always_TT8 小时前
【Python 日志记录:logging 模块入门】
开发语言·python·php
画面无声8 小时前
STM32的SPI通信原理与练习记录
c语言·stm32·单片机·嵌入式硬件·学习
xcLeigh8 小时前
Go入门:变量声明的五种方式详解
java·开发语言·golang
weixin_456808388 小时前
【沁恒蓝牙开发】IAP升级流程
c语言·单片机·嵌入式硬件
zmzb01038 小时前
C++课后习题训练记录Day175
开发语言·c++
脱胎换骨-军哥9 小时前
C++ 代码规范与格式化指南
开发语言·c++·代码规范
枕星而眠10 小时前
C++ STL Map容器完全指南:从有序红黑树到无序哈希表
java·开发语言
geats人山人海10 小时前
数据结构第六章c语言 树的存储下二叉树的概念和存储
c语言·数据结构·算法