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
相关推荐
一起养小猫5 分钟前
LeetCode100天Day9-无重复字符的最长子串与赎金信
java·开发语言·数据结构·leetcode
wjs202410 分钟前
Go 语言类型转换
开发语言
菩提祖师_11 分钟前
基于Java的物联网智能交通灯控制系统
java·开发语言·物联网
公众号:ITIL之家16 分钟前
服务价值体系重构:在变化中寻找不变的运维本质
java·运维·开发语言·数据库·重构
zhaokuner22 分钟前
01-领域与问题空间-DDD领域驱动设计
java·开发语言·设计模式·架构
青岛少儿编程-王老师30 分钟前
CCF编程能力等级认证GESP—C++8级—20251227
java·开发语言·c++
charlie11451419134 分钟前
FreeRTOS:中断(ISR)与 RTOS 安全 API
开发语言·c·freertos·实时操作系统
一路往蓝-Anbo38 分钟前
STM32单线串口通讯实战(三):协议层设计 —— 帧结构、多机寻址与硬件唤醒
c语言·开发语言·stm32·单片机·嵌入式硬件·物联网
Love Song残响40 分钟前
高效自动化清理临时文件方案
java·开发语言·spring
古城小栈44 分钟前
Rust 中符号语法 一文全晓
开发语言·后端·rust