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
相关推荐
达帮主8 分钟前
16. C语言二级指针
c语言·开发语言·汇编·青少年编程
難釋懷21 分钟前
JavaScript基础-获取元素
开发语言·javascript
衫水23 分钟前
1.FastAPI简介与安装
开发语言·python·fastapi
代码不停31 分钟前
C语言——结构体、联合、枚举
c语言·开发语言·windows
wen__xvn41 分钟前
每日一题洛谷P1106 删数问题c++
开发语言·c++·算法
小白学大数据1 小时前
Superagent 异步请求:如何处理复杂的 HTTP 场景
开发语言·网络·python·网络协议·http
_GR1 小时前
2020年蓝桥杯第十一届C&C++大学B组(第二次)真题及代码
c语言·数据结构·c++·算法·蓝桥杯
Bczheng11 小时前
C++ 语法之函数和函数指针
开发语言·c++
C语言小火车1 小时前
Redis 10大核心场景实战手册:从缓存加速到分布式锁的全面解析
c语言·开发语言·数据库·c++·redis
lisw051 小时前
【Linux】Bash是什么?怎么使用?
linux·开发语言·bash