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
相关推荐
come1123420 分钟前
现代前端技术栈关系详解 (PHP 开发者特供版)
开发语言·前端·php
yong999020 分钟前
基于互信息的Matlab多模态医学图像配准实现
开发语言·matlab
E***q53938 分钟前
JavaScript数据挖掘开发
开发语言·javascript·数据挖掘
Lxinccode1 小时前
python(59) : 多线程调用大模型ocr提取图片文本
开发语言·python·图片提取文字·批量提取文件·多线程ocr
自由日记1 小时前
python简单线性回归
开发语言·python·线性回归
程序员-周李斌1 小时前
Java NIO [非阻塞 + 多路复用解]
java·开发语言·开源软件·nio
猪八戒1.01 小时前
onenet接口
开发语言·前端·javascript·嵌入式硬件
h***83931 小时前
JavaScript开源
开发语言·javascript·ecmascript
Z***25801 小时前
JavaScript虚拟现实案例
开发语言·javascript·vr
Halo_tjn2 小时前
Set集合专项实验
java·开发语言·前端·python