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
相关推荐
charlie1145141913 分钟前
深入理解CC++的编译与链接技术9:动态库细节
c语言·开发语言·c++·学习·动态库
席之郎小果冻3 分钟前
【03】【创建型】【聊一聊,单例模式】
开发语言·javascript·单例模式
god007 分钟前
Selenium等待判断元素页面加载完成
java·开发语言
isyoungboy9 分钟前
c++使用win新api替代DirectShow驱动uvc摄像头,可改c#驱动
开发语言·c++·c#
Dxy123931021611 分钟前
python如何去掉字符串中最后一个字符
开发语言·python
云和数据.ChenGuang23 分钟前
`post_max_size`、`max_execution_time`、`max_input_time` 是 **PHP 核心配置参数**
开发语言·mysql·php·zabbix·mariadb
听风吟丶25 分钟前
Java HashMap 深度解析:从底层结构到性能优化实战
java·开发语言·性能优化
ZBritney31 分钟前
JAVA中的异常二
java·开发语言
weixin_3077791332 分钟前
Jenkins Pipeline:Groovy插件全解析:从原理到实战应用
开发语言·ci/cd·自动化·jenkins·etl
EXtreme3536 分钟前
【数据结构】打破线性思维:树形结构与堆在C语言中的完美实现方案
c语言·数据结构·算法··heap·完全二叉树·topk