alloc complex data in c, and access in fortran

a.f90

bash 复制代码
program main
        use iso_c_binding
        implicit none
        type(c_ptr) :: ADD1
        type(c_ptr) :: c_ptr1
        external ADD1
        integer :: i
        complex :: z
        complex, pointer :: S(:)

        c_ptr1 = ADD1( )

        call c_f_pointer(c_ptr1, S, [10])
        print *, 'Array from C function: '
        do i = 1, 5
        print *, S(i)
        end do
        !        z = (1.0, 7.0)  ! 0 is the real part, 5.0 is the imaginary part
        !        print *, 'Complex number: ', z
end program

b.c

bash 复制代码
# include <stdlib.h>
# include <stdio.h>

float* add1_( )
{
        int n = 10; // size of the array
        float *arr = (float *)malloc(n * sizeof(float)); // 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("%f ", arr[i]); // Print each element
        }
        printf("\n");
        return (float *) arr;
}

Makefile

bash 复制代码
all:
        gcc -c b.c -O0 -g
        gfortran a.f90 b.o -O0 -g -o a.out
相关推荐
每天回答3个问题9 分钟前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
BenChuat17 分钟前
Java常见排序算法实现
java·算法·排序算法
伍哥的传说22 分钟前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
元亓亓亓38 分钟前
LeetCode热题100--105. 从前序与中序遍历序列构造二叉树--中等
算法·leetcode·职场和发展
小莞尔41 分钟前
【51单片机】【protues仿真】基于51单片机的篮球计时计分器系统
c语言·stm32·单片机·嵌入式硬件·51单片机
小莞尔1 小时前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
纪元A梦1 小时前
贪心算法在SDN流表优化中的应用
算法·贪心算法
liujing102329291 小时前
Day03_刷题niuke20250915
c语言
我是菜鸟0713号1 小时前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_1 小时前
QT(4)
开发语言·汇编·c++·qt·算法