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
相关推荐
\光辉岁月/10 小时前
3.包装类
java·开发语言·包装类
FRing0311 小时前
JavaScript入门到精通二十四(正则表达式、元字符、修饰符)
开发语言·前端·javascript·正则表达式
西索斯coding11 小时前
Grok 4.7 调用一直 401 怎么办?不是 Key 过期,是 Authorization 头格式问题——排查全流程 + 修复示例
服务器·开发语言·ai·php
himobrinehacken11 小时前
位运算揭秘:左右移与符号位陷阱
c语言·c++·算法·安全
SEO_juper11 小时前
hreflang 审计工具:外贸多语言站谷歌SEO的隐性杀手
开发语言·人工智能·爬虫·python·seo
WJ.Polar12 小时前
final、单例类、枚举类、抽象类、接口
java·开发语言
小羊没烦恼!12 小时前
C#综合揭秘——Entity Framework 并发处理详解
java·开发语言·前端·javascript·数据库·mysql·c#
艾iYYY12 小时前
【无标题】
linux·开发语言·网络·操作系统
NetX行者12 小时前
Rust 初体验:一个全栈工程师的编译器“毒打“笔记
开发语言·笔记·rust
我就是不信13 小时前
Java8 lambda 表达式 forEach 如何提前终止?
开发语言·windows·python