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
相关推荐
Navigator_Z1 分钟前
LeetCode //C - 1187. Make Array Strictly Increasing
c语言·算法·leetcode
charlie1145141917 分钟前
IMX6ULL WM8960 的移植——前置介绍
开发语言·c++·开源项目·嵌入式linux
迷迭香yy30 分钟前
Python实战:涨停板“假封板”识别系统的工程实现
开发语言·人工智能·python
charlie11451419131 分钟前
Cinux是如何管理进程的 —— 上下文与调度
开发语言·c++·操作系统·开源项目
-银雾鸢尾-1 小时前
C#中的协变和逆变
开发语言·c#
阿米亚波1 小时前
【C++ 异常处理】try-catch
开发语言·c++·笔记·try-catch
旖旎夜光1 小时前
C++(内存管理)
开发语言·c++·学习
≮傷£≯√1 小时前
QT配置FFmpeg
开发语言·qt·ffmpeg
别动我齐刘海2 小时前
“三层同步审计”判定掉帧缺失
c语言·c++·人工智能·深度学习·学习·机器学习·机器人
十月的皮皮2 小时前
STM32从零到量产开发:四路继电器工业控制模块开发 -上位机主窗口设计说明
c语言·stm32·单片机·stm32cubemx