如何使用CTYPES界面将Python库中的内部数据阵列指针进入Python
我有大型的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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论