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
相关推荐
吃好睡好便好4 分钟前
MATLAB仿真框图2
开发语言·matlab·仿真·simulink
小当家.1051 小时前
MCP 协议深度解析:AI 领域的 USB-C 接口
开发语言·人工智能·agent·tool·mcp
accept 99%1 小时前
python版提取 PDF 的常用第三方库与工具
开发语言·python·pdf
lzhdim1 小时前
C# 通过 Windows API 实现进程内存读写操作
开发语言·windows·c#
-银雾鸢尾-1 小时前
C#中的预处理指令
开发语言·c#
Livia要学习1 小时前
Python面向对象三大特性:封装、继承、多态
开发语言·python
dalong102 小时前
Savitzky-Golay 的C# 实现
开发语言·kotlin·c#
十月的皮皮2 小时前
STM32从零到量产开发:四路继电器工业控制模块开发 -上位机 Program.cs 应用程序入口设计说明
c语言·stm32·单片机·stm32cubemx·hal库
坚持编程的菜鸟2 小时前
模拟实现memcpy
c语言·算法·模拟实现my_memcpy
show4332 小时前
多格式导出怎么做?2026免费小程序TXT/SRT实践
开发语言·小程序·c#