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
相关推荐
python猿6 分钟前
打卡Python王者归来--第30天
开发语言·python
qq_334903157 分钟前
嵌入式C++驱动开发
开发语言·c++·算法
阿贵---18 分钟前
C++代码规范化工具
开发语言·c++·算法
暮冬-  Gentle°26 分钟前
自定义内存检测工具
开发语言·c++·算法
一直都在57227 分钟前
Java死锁
java·开发语言
娇娇yyyyyy29 分钟前
QT编程(15): Qt 按键事件和定时器事件
开发语言·qt
2501_9454248044 分钟前
C++编译期矩阵运算
开发语言·c++·算法
yy我不解释1 小时前
关于comfyui的mmaudio音频生成插件时时间不一致问题(三)
开发语言·python·ai作画·音视频·comfyui
2301_815482931 小时前
C++中的类型标签分发
开发语言·c++·算法
SuperEugene1 小时前
Vue3 模板语法规范实战:v-if/v-for 不混用 + 表达式精简,避坑指南|Vue 组件与模板规范篇
开发语言·前端·javascript·vue.js·前端框架