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
相关推荐
yyy(十一月限定版)15 小时前
224redfg
c语言
2601_9628857216 小时前
如何用 Python 自动识别股票的支撑位与压力位?
开发语言·python
爱吃奥利奥_wen16 小时前
面向对象三板斧:封装、继承、多态,到底在“装“什么、“承“什么、“变“什么?
开发语言·经验分享·c#
我可能是个假开发17 小时前
FTP Unicode 文件名导致 `550` 的问题分析与解决方案
java·开发语言·spring
小师兄吃牛肉17 小时前
C语言中的nullptr有必要吗
c语言·c++·算法
WL学习笔记18 小时前
日期类(C++)
开发语言·c++·日期类实现
谢亮_vipxieliang19 小时前
Go map与结构体的正确使用
开发语言·golang·哈希算法
H.莓飛19 小时前
【C++】命名空间、缺省参数、函数重载与引用
linux·开发语言·c++·visual studio
lhbweilai19 小时前
深挖FreeRTOS内核实现(三)
c语言·stm32·单片机
xxwl58519 小时前
数据结构知识点和代码实现总结(C语言实现)
c语言·开发语言·数据结构