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
相关推荐
lly2024065 分钟前
组合模式(Composite Pattern)
开发语言
游乐码25 分钟前
c#泛型约束
开发语言·c#
Dontla37 分钟前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen37 分钟前
python rest请求、requests
开发语言·python
铁东博客43 分钟前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
baidu_huihui1 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳1 小时前
Python从入门到精通day63
开发语言·python
lbb 小魔仙1 小时前
Python_RAG知识库问答系统实战指南
开发语言·python
weixin_446023561 小时前
C语言:面向过程、应用底层开发、跨平台的通用程序设计语言
c语言·跨平台·数据类型·底层开发·面向过程
551只玄猫2 小时前
【数学建模 matlab 实验报告13】主成分分析
开发语言·数学建模·matlab·课程设计·主成分分析