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
相关推荐
孟浩浩1 小时前
JAVA SpringAI+阿里云百炼应用开发
java·开发语言·阿里云
碧蓝的水壶1 小时前
数据转换过程
java·开发语言·windows
2501_947575807 小时前
计算机毕业设计之jsp开山车行二手车交易系统
java·开发语言·hadoop·python·信息可视化·django·课程设计
骑士雄师8 小时前
java面试题 4:鉴权
java·开发语言
时间的拾荒人9 小时前
C语言字符函数与字符串函数完全指南
c语言·开发语言
2501_948106919 小时前
计算机毕业设计之基于jsp教科研信息共享系统
java·开发语言·信息可视化·spark·课程设计
持力行9 小时前
C/C++ 中的 char*:它标识数组吗?为什么能用下标访问?
c语言·c++
取经蜗牛9 小时前
Python 第一阶段完全指南:从零到第一个实用工具
开发语言·python
dog25010 小时前
从重尾到截断流量模型的演进
开发语言·php
qq_4017004110 小时前
Qt QSS 完全入门写出漂亮界面以及解决样式不生效问题
开发语言·qt