|
1 | 1 | require('arrayfire.lib')
|
2 |
| -require('class') |
| 2 | +require('arrayfire.defines') |
3 | 3 | local ffi = require( "ffi" )
|
4 | 4 |
|
5 | 5 | local funcs = {}
|
@@ -61,3 +61,66 @@ funcs[34] = [[
|
61 | 61 | ]]
|
62 | 62 |
|
63 | 63 | af.lib.cdef(funcs)
|
| 64 | + |
| 65 | +local Array = {} |
| 66 | +Array.__index = Array |
| 67 | + |
| 68 | +local c_dim4_t = af.ffi.c_dim4_t |
| 69 | +local c_uint_t = af.ffi.c_uint_t |
| 70 | +local c_array_p = af.ffi.c_array_p |
| 71 | + |
| 72 | +local add_finalizer = function(arr_ptr) |
| 73 | + return ffi.gc(arr_ptr[0], af.clib.af_release_array) |
| 74 | +end |
| 75 | + |
| 76 | +Array.__init = function(data, dims, dtype, source) |
| 77 | + local self = setmetatable({}, Array) |
| 78 | + |
| 79 | + if data then |
| 80 | + assert(af.istable(data)) |
| 81 | + end |
| 82 | + |
| 83 | + if dims then |
| 84 | + assert(af.istable(dims)) |
| 85 | + end |
| 86 | + |
| 87 | + c_dims = c_dim4_t(dims or (data and {#data} or {})) |
| 88 | + c_ndims = c_uint_t(dims and #dims or (data and 1 or 0)) |
| 89 | + |
| 90 | + nelement = 1 |
| 91 | + for i = 1,tonumber(c_ndims) do |
| 92 | + nelement = nelement * c_dims[i - 1] |
| 93 | + end |
| 94 | + nelement = tonumber(nelement) |
| 95 | + |
| 96 | + local atype = dtype or af.dtype.f32 |
| 97 | + local res = c_array_p() |
| 98 | + if not data then |
| 99 | + af.clib.af_create_handle(res, c_ndims, c_dims, atype) |
| 100 | + else |
| 101 | + c_data = ffi.new(af.dtype_names[atype + 1] .. '[?]', nelement, data) |
| 102 | + af.clib.af_create_array(res, c_data, c_ndims, c_dims, atype) |
| 103 | + end |
| 104 | + self.__arr = add_finalizer(res) |
| 105 | + return self |
| 106 | +end |
| 107 | + |
| 108 | +Array.__tostring = function(self) |
| 109 | + return 'arrayfire.Array\n' |
| 110 | +end |
| 111 | + |
| 112 | +Array.get = function(self) |
| 113 | + return self.__arr |
| 114 | +end |
| 115 | + |
| 116 | +setmetatable( |
| 117 | + Array, |
| 118 | + { |
| 119 | + __call = function(cls, ...) |
| 120 | + return cls.__init(...) |
| 121 | + end |
| 122 | + } |
| 123 | +) |
| 124 | + |
| 125 | +af.Array = Array |
| 126 | +af.ffi.add_finalizer = add_finalizer |
0 commit comments