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
相关推荐
shix .几秒前
反控制台,函数,反调试
开发语言·前端·javascript
roman_日积跬步-终至千里1 分钟前
【Java多并发编程】CompletableFuture 使用指南(实战篇):从场景到优化
java·开发语言
crossaspeed2 分钟前
Java-List,Set,Map(八股)
java·开发语言·list
LawrenceLan3 分钟前
Flutter 零基础入门(十八):StatefulWidget 生命周期初识
开发语言·前端·flutter·dart
代码or搬砖3 分钟前
java并发编程
java·开发语言
小李独爱秋8 分钟前
计算机网络经典问题透视:IP电话的通话质量与哪些因素有关?
服务器·开发语言·网络·网络协议·tcp/ip·计算机网络
BHXDML11 分钟前
第九章: STL 容器基础(C++)
开发语言·c++
董世昌4114 分钟前
什么是暂时性死区?
开发语言·前端·javascript
茉莉玫瑰花茶20 分钟前
C++11 扩展 - 模板元编程
开发语言·c++
六毛的毛23 分钟前
hot100 python解法合集
开发语言·python