如何使用 ISO C BINDINGS 将结构数组转换为派生类型数组?

问题描述

我有以下测试 C 库:

#include <stdlib.h>

struct mystruct {
    int a;
    double  b;
};

struct mystruct *return_array_of_structs(int *size);

struct mystruct *return_array_of_structs(int *size) {

    int i;
    struct mystruct *ptr;
    ptr = malloc(sizeof(struct mystruct)*10);
    
    for(i=0; i<10; i++) {
        ptr[i].a = i+1;
        ptr[i].b = (i+1)*1.0L;
    }
    
    *size=10;
    return ptr;
}

以及以下打算使用 f2py 编译的模块:

module test_c_lib

        use iso_c_binding
        implicit none

        type :: t_mystruct
            integer :: a
            real(8) :: b
        end type
        
contains

        subroutine test()

                use iso_c_binding
                
                type(c_ptr)     :: ret_c_ptr            
                integer         :: length
                
                ! Interface to C function
                interface                        
                        type(c_ptr) function c_return_array_of_structs(a) bind(C,name="return_array_of_structs")
                                import
                                integer(c_int) :: a
                        end function
                end interface

                ! Call C function               
                ret_c_ptr = c_return_array_of_structs(length)

        
        end subroutine

end module

下面的 makefile 编译了这个:

f_mod.so:       f_mod.f90 c_lib.o
                f2py -c f_mod.f90 c_lib.o -m f_mod

c_lib.o:        c_lib.c
                gcc -c -fpic c_lib.c -o c_lib.o

我可以在 Python 中正常加载库并执行 test() 子例程没有问题。

import f_mod
f_mod.test_c_lib.test()

但我不知道如何将 ret_c_ptr 转换为派生类型 t_mystruct 的数组,我通常可以在 Fortran 中将其作为数组进行操作。任何提示? 注意:问题与 iso c bindings 和 Fortran 有关,而不是 f2py 或其与 Python 的集成。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)