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
相关推荐
worilb5 分钟前
Java/JVM 常见诊断文件对比
java·开发语言
ttwuai8 分钟前
Go 后台初始化 MySQL 脚本失败怎么办?先查 DDL 还是生成配置
开发语言·mysql·golang
2601_9628857210 分钟前
如何用 Python 做 A 股全市场扫描选股?(多条件筛选实战)
开发语言·python
奈斯先生Vector22 分钟前
AIGC 视频生成换个拍法:用 Kling Video 把一张人物图变成可剪辑的短故事
开发语言·人工智能·windows·python·aigc·音视频
一木 之林24 分钟前
五、C++ 新特性、关键字与编译原理(进阶)(一)
c语言·开发语言·c++
秋名RG30 分钟前
Java IO 体系深度剖析:从流式编程到 JDK 21 高并发陷阱
java·开发语言
Pocker_Spades_A40 分钟前
Python快速入门专业版(五十九):re实战——用正则爬取豆瓣电影Top250(全流程解析)
开发语言·python
whitelbwwww1 小时前
c++ 多线程
开发语言·c++·算法
乌药ice1 小时前
c#中一个多线程安全的HashSet
开发语言·c#
秋名RG1 小时前
Java 异常处理全攻略:从入门到实战(JDK 21 版)
java·开发语言