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
相关推荐
在爪洼山玩泥巴18 分钟前
fastjson2 JSONPath 取不存在路径,为什么会抛 “not support”?
java·开发语言·jsonpath·fastjson
星落梦生10 小时前
SpringAOP基础笔记(7)
java·开发语言
曹牧12 小时前
Java:“刷新雪崩”
java·开发语言
郝学胜-神的一滴12 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
西西弗Sisyphus13 小时前
C++ explicit 关键字工程实践
开发语言·c++
戊本菌14 小时前
进程(三)进程优先级:谁先上 CPU
linux·c语言·硬件架构
郝学胜-神的一滴15 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
feixing_fx15 小时前
原始类型与引用类型:赋值时到底复制了什么
开发语言·前端·javascript·前端框架
wuyk55515 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
神明不懂浪漫16 小时前
【第八章】多线程(一)
java·开发语言·经验分享·笔记