如何使用CTYPES界面将Python库中的内部数据阵列指针进入Python

发布于 2025-01-24 17:51:11 字数 973 浏览 4 评论 0原文

我有大型的fotran库(用于量子化学),它在内部存储可变bbnkre,它是包含波函数系数的3D阵列。 我想从Python 中访问此内部数组(既读写/修改),而无需复制该数组的内容

我要避免复制的主要原因是要节省记忆和复制整个数组所需的时间,当我想修改其中的一部分时。

目前,我有关注,但似乎没有用:

在fortran中:

! somewhere in module
real, dimension (:, :, :), allocatable, target :: bbnkre

...

!interface subroutine exposed to library interface
subroutine firecore_getPointer_wfcoef( bbnkre_ ) bind(c, name='firecore_getPointer_wfcoef')
    use iso_c_binding
    use density
    implicit none
    type(C_PTR),      intent(out) :: bbnkre_
    bbnkre_ = c_loc( bbnkre ) 
end subroutine 

python

array3d  = np.ctypeslib.ndpointer(dtype=np.double, ndim=3, flags='CONTIGUOUS')
lib.firecore_getPointer_wfcoef.argtypes  = [array3d] 
lib.firecore_getPointer_wfcoef.restype   =  None
def firecore_getPointer_wfcoef(bbnkre):
    return lib.firecore_getPointer_wfcoef(bbnkre) 

I have large Fotran library (for quantum chemistry) which internally stores variable bbnkre which is 3D array containing coefficients of wavefunction.
I want to get access to this internal array (both read and write/modify) from python without copying the content of that array.

Main reason why I want to avoid copying is to save memory and time required for copying the whole array, when I want to modify just part of it.

Currently I have following, but it does not seem to work:

In Fortran:

! somewhere in module
real, dimension (:, :, :), allocatable, target :: bbnkre

...

!interface subroutine exposed to library interface
subroutine firecore_getPointer_wfcoef( bbnkre_ ) bind(c, name='firecore_getPointer_wfcoef')
    use iso_c_binding
    use density
    implicit none
    type(C_PTR),      intent(out) :: bbnkre_
    bbnkre_ = c_loc( bbnkre ) 
end subroutine 

In Python

array3d  = np.ctypeslib.ndpointer(dtype=np.double, ndim=3, flags='CONTIGUOUS')
lib.firecore_getPointer_wfcoef.argtypes  = [array3d] 
lib.firecore_getPointer_wfcoef.restype   =  None
def firecore_getPointer_wfcoef(bbnkre):
    return lib.firecore_getPointer_wfcoef(bbnkre) 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文