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
相关推荐
rainFFrain14 分钟前
qt显示类控件---QProgressBar
开发语言·qt
鑫—萍15 分钟前
C/C++精品算法——双指针(1)
c语言·c++·算法
rainFFrain21 分钟前
qt输入类控件---QComboBox/QSpinBox
开发语言·qt
2501_9411118925 分钟前
低延迟系统C++优化
开发语言·c++·算法
未来之窗软件服务38 分钟前
自建开发工具IDE(二)文件托拽读取——东方仙盟炼气期
开发语言·前端·javascript·仙盟创梦ide·东方仙盟
Hello_WOAIAI1 小时前
4.2 python多线程编程:threading 模块深度解析
开发语言·python
2501_941111991 小时前
C++中的装饰器模式变体
开发语言·c++·算法
树下水月2 小时前
python 连接hive2 数据库
开发语言·数据库·python
Tom4i2 小时前
Kotlin 中的 inline 和 reified 关键字
android·开发语言·kotlin
凄戚2 小时前
bash和命令
开发语言·chrome·bash