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
相关推荐
饮水桶_T33 分钟前
Git笔记
开发语言·笔记·算法
国科安芯34 分钟前
让每一瓦热都听话:航天器主动热控系统CANFD控制网络的可靠性设计
开发语言·网络·单片机·嵌入式硬件·信息与通信·抗辐射·载荷
CoderYanger42 分钟前
Java EE 进阶:12.Spring AOP(第一弹)
java·开发语言·spring boot·后端·spring·java-ee·交互
松仔log1 小时前
Kotlin中级——KMP
android·开发语言·kotlin
H H.1 小时前
Java笔记:String字符串
java·开发语言·经验分享·笔记·其他
鲸渔2 小时前
【AI Agent系列课程26-Python 基础26】复盘:Python 接口开发知识清单
开发语言·python·ai编程
sharemylove2 小时前
Java 异常处理 学习笔记
java·开发语言·经验分享·笔记·学习
西西弗Sisyphus2 小时前
Qt QML 程序是怎么跑起来的(1)qml-only
开发语言·c++·qt
Navigator_Z3 小时前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode
发疯的技术鼠3 小时前
第21篇-联合和枚举
c语言