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
相关推荐
echome88810 分钟前
JavaScript Promise 与 async/await 实战:5 个高频异步编程场景的优雅解决方案
开发语言·javascript·ecmascript
xcLeigh32 分钟前
IoTDB Java 原生 API 实战:SessionPool 从入门到精通
java·开发语言·数据库·api·iotdb·sessionpool
杜子不疼.33 分钟前
Java 智能体学习避坑指南:3 个常见误区,新手千万别踩,高效少走弯路
java·开发语言·人工智能·学习
冬天vs不冷34 分钟前
为什么 Java 不让 Lambda 和匿名内部类修改外部变量?final 与等效 final 的真正意义
android·java·开发语言
星河耀银海34 分钟前
JAVA 多线程编程:从基础原理到实战应用
java·开发语言·php
星河耀银海34 分钟前
JAVA IO流:从基础原理到实战应用
java·服务器·开发语言
摸鱼仙人~1 小时前
Math.js 使用教程
开发语言·javascript·ecmascript
HAPPY酷1 小时前
Python高阶开发:从底层原理到架构设计的进阶之路
开发语言·python
爱编码的小八嘎1 小时前
c.语言完美演绎6-22
c语言
疯狂打码的少年2 小时前
【Day 6 Java转Python】字符串处理的“降维打击”
java·开发语言·python