Skip navigation.

Posts tagged with "ctypes"

multi-dimension array in ctypes

, ,

multi-dimension array definition in ctypes is a few confusing, let's see an example.

I want to define an integer array x(5,3) (fortran style declaration), then corresponding python code is

from ctypes import *
xarray = c_int * 3 * 5
x = xarray()

because ctypes parse the definition as (c_int*3)*5, so first dimension 5, and second 3. the order is reversed. it's confusing. Thomas Helle has given a function to make it clearer. see the code listed below.

from ctypes import *

def create_array_type(type, dimensions):
    for d in dimensions[::-1]:
        print d
        type = type*d
    return type

# array 2 dimension (5,3)
xarray = create_array_type(c_int, (5,3))
x = xarray()

Call Fortran Dll from Python with ctypes (IV)

, ,

数组array在Fortran Dll中总是按照地址传送的,因此无论如何在ctypes中都要用byref()来操作。而ctypes对C中array的描述就是一个相同数据类型的序列(sequence)

使用内置数据类型构造数组

myarray = c_int*10       # 定义一维整型数组,大小为10
myarray = c_double*42    # 定义一维双精度浮点数数组,大小为42

x = myarray()            # 实例化


一维数组

一维数组的构造使用数据类型乘以一个数值,该数值代表数组大小
# array  1 dimension
print 'test 1-dimension array'
n = c_int(10)
xarray = c_int * n.value
x = xarray(1,2,3,4,5,6,7,8,9,10)
m = c_int(7)
yarray = c_double*m.value
y = yarray()
d.array1(byref(n), byref(x), byref(m), byref(y))

print x
for i in y: print i;

相应fortran代码
subroutine array1(n, x, m, y)
  !DEC$ ATTRIBUTES DLLEXPORT, ALIAS:'array1' :: array1
  integer :: n
  integer, dimension(n) :: x
  real(8), dimension(m) :: y

  if (m>n) then
     y(1:n) = x
  else if (m<n) then
     y = x(1:m)
  endif
end subroutine array1

二维数组

二位数组的构造是用某个数据类型乘以多个数值,这些数值分别对应各个维数
 
# array 2 dimension
print 'test 2-dimension array'
m = c_int(3)
n = c_int(5)
xarray = c_int * m.value * n.value
x = xarray()

print x
d.array2(byref(n), byref(m), byref(x))

for j in range(n.value):
    for i in range(m.value):
        print j, i, x[j][i]

对应fortran代码
subroutine array2(m, n, x)
  !DEC$ ATTRIBUTES DLLEXPORT, ALIAS:'array2' :: array2
  integer :: n, m
  integer, dimension(m, n) :: x
 
  do i=1, m  ! 5 
    do j = 1, n  ! 3
            x(i,j) = i*j
    end do
  end do

end subroutine array2


ctypes中定义的二维数组看起来有点儿奇怪是不是:sst:

ctypes + Numpy

, ,

ctypes已经进入python2.5标准库,不过现在的文档有些乱,作者还在赶工撰写文档。

Numpy还在为他们的array interface能够进入python而努力中,现在的api还不太稳定,变来变去。而且和其他numeric, numarray的文档混来混去,让人头晕。再过一段时间1.0释放的时候,应该是一个稳定的版本了吧。

目前让Numpy与ctypes合作的方法有些麻烦,用起来也有些混乱,scipy的cookbook中有相关用法,应该是能够找到的资料中比较详细的了 http://www.scipy.org/Cookbook/Ctypes

估计近期ctypes不太可能主动适应numpy,我们用户可有的麻烦了。