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
相关推荐
Bayi·2 小时前
前端面试场景题
开发语言·前端·javascript
碎梦归途2 小时前
23种设计模式-结构型模式之享元模式(Java版本)
java·开发语言·jvm·设计模式·享元模式
Xiaoyu Wang2 小时前
Go协程的调用与原理
开发语言·后端·golang
bigear_码农2 小时前
python异步协程async调用过程图解
开发语言·python·线程·进程·协程
知识分享小能手3 小时前
JavaScript学习教程,从入门到精通,Ajax与Node.js Web服务器开发全面指南(24)
开发语言·前端·javascript·学习·ajax·node.js·html5
凌叁儿3 小时前
Python 的 datetime 模块使用详解
开发语言·python
谁家有个大人3 小时前
Python数据清洗笔记(上)
开发语言·笔记·python·数据分析
MurphyStar4 小时前
UV: Python包和项目管理器(从入门到不放弃教程)
开发语言·python·uv
阿让啊4 小时前
单片机获取真实时间的实现方法
c语言·开发语言·arm开发·stm32·单片机·嵌入式硬件
FightingLod4 小时前
STM32版I²C相亲指南(软件硬件双修版)
c语言·stm32·单片机