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
相关推荐
Reload.10 分钟前
GJ航司,验证码网易易盾 JS逆向 纯算轨迹
开发语言·前端·javascript
人道领域24 分钟前
【LeetCode刷题日记】贪心算法理论与实战:455.分发饼干最优解
java·开发语言·数据结构·算法·leetcode·贪心算法
xin_yao_xin29 分钟前
Conda 环境的 CUDA PATH 配置指南
开发语言·python·conda·cuda
he___H34 分钟前
基于LCEL的联想
开发语言·python·langchain
阿pin1 小时前
Android随笔-神经系统Handler
android·java·开发语言·handler
布朗克1681 小时前
Go 入门到精通-09-复合类型之Map
开发语言·后端·golang·map
zh_xuan1 小时前
c++ Expected用法
开发语言·c++·expected
ch.ju1 小时前
Java程序设计(第3版)第四章——final修饰的方法和类
java·开发语言
极***技1 小时前
2026云原生核心!Go高并发限流实战,从原理到落地
开发语言·云原生·golang