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
相关推荐
kaiaaaa2 分钟前
算法训练第十一天
数据结构·算法
?!7144 分钟前
算法打卡第18天
c++·算法
flyair_China12 分钟前
【云架构】
开发语言·php
springfe010117 分钟前
构建大顶堆
前端·算法
Chef_Chen19 分钟前
从0开始学习R语言--Day20-ARIMA与格兰杰因果检验
开发语言·学习·r语言
zh_xuan19 分钟前
c++ std::pair
开发语言·c++
CodeWithMe41 分钟前
【C/C++】EBO空基类优化介绍
开发语言·c++
404.Not Found1 小时前
Day46 Python打卡训练营
开发语言·python
love530love1 小时前
【PyCharm必会基础】正确移除解释器及虚拟环境(以 Poetry 为例 )
开发语言·ide·windows·笔记·python·pycharm
凌辰揽月1 小时前
Web后端基础(基础知识)
java·开发语言·前端·数据库·学习·算法