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
相关推荐
重生之我要当java大帝几秒前
java微服务-尚医通-编写医院设置接口下
java·开发语言·sql
寻找华年的锦瑟几秒前
Qt-QDir
开发语言·qt
小妖66613 分钟前
vscode 怎么运行 c++ 文件
开发语言·c++
weixin_3077791314 分钟前
在 Microsoft Azure 上部署 ClickHouse 数据仓库:托管服务与自行部署的全面指南
开发语言·数据库·数据仓库·云计算·azure
鱼鱼说测试16 分钟前
Linux下运行Jmeter
开发语言·python
鱼鱼说测试25 分钟前
postman功能接口测试
开发语言·lua
Achou.Wang26 分钟前
源码分析 golang bigcache 高性能无 GC 开销的缓存设计实现
开发语言·缓存·golang
ytttr87342 分钟前
C语言实现Modbus TCP/IP协议客户端-服务器
服务器·c语言·tcp/ip
绵羊20231 小时前
R语言绘制热图
开发语言·r语言
小冯记录编程1 小时前
深入解析C++ for循环原理
开发语言·c++·算法