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
相关推荐
aaaameliaaa5 小时前
字符函数和字符串函数
c语言·笔记·算法
夜月yeyue6 小时前
AUTOSAR CP 从上电到 Runnable
c语言·网络·tcp/ip·车载系统
微学AI6 小时前
一根针指向所有方向:挂谷猜想对 LLM Agent 技能-记忆架构的启示
开发语言·人工智能·架构·挂谷猜想
豆瓣鸡7 小时前
算法日记 - Day3
java·开发语言·算法
白白白小纯7 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
韭菜炒鸡肝天8 小时前
VTK开发笔记(一):VTK介绍,Qt..+VSx+VTK.编译
开发语言·笔记·qt
小羊先生car8 小时前
RTOS-F429-HAL-绝对延时和相对延时(2026/7/31)
c语言·rtos
Aaron - Wistron8 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
Dxy12393102169 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python
05664610 小时前
Python康复训练——常用标准库
开发语言·python·学习