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
相关推荐
Zwawa19 分钟前
断电后参数为什么全没了:把小车配置安全地存进 Flash
c语言·单片机·嵌入式
zbguolei35 分钟前
第002篇 · 战火中的电子黎明
开发语言·php
sean_wang1242 分钟前
Rust 轻量级虚拟机 smolvm 实战:200ms 冷启动、OCI 镜像直跑、单文件打包
开发语言·后端·rust·大鲸华章
战6171 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
羊在吃青草2 小时前
C语言之数组
c语言·数据结构
郝学胜-神的一滴2 小时前
量化交易从入门到精通 05:策略从哪来
开发语言·python·numpy·pandas·scikit-learn·matplotlib·scipy
烟烟Abandon2 小时前
FFmpeg开发基础之 C 语言中的文件操作
c语言·ffmpeg
zbguolei2 小时前
第001篇 · 算盘与差分机
开发语言·php
ZHOUPUYU3 小时前
PHP 8.4 新特性实战指南:从属性钩子到异步编程
开发语言·php