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
相关推荐
是隼人1 小时前
buuctf-pwn PWN8题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
GG-_-Bond1 小时前
9.1kv存储持久化模拟面试
linux·c语言·数据结构·c++
Ivanqhz1 小时前
Unigram 算法
开发语言·人工智能·python·深度学习·mlir
Jazz_z2 小时前
如何用 C# 读取 Word 中的表格数据
开发语言·c#
无敌贵点大王2 小时前
RTThread学习记录10——C语言实现面向对象的编程
c语言·stm32·学习·链表
郝学胜-神的一滴2 小时前
C++20模板元编程 04:变量模板 别名模板与模板Lambda实战
服务器·开发语言·数据结构·c++·程序人生
驭渊的小故事2 小时前
Java 项目-jckson序列化工具
java·开发语言
君顾12 小时前
上海24小时自助健身房系统开发实战指南:从架构设计到功能实现
java·开发语言·健身房
qq_344920562 小时前
Qt事件过滤器
开发语言·c++·qt