用户登录
用户注册

分享至

C#+无unsafe的非托管大数组示例详解(large unmanaged array in c# without ‘unsafe’ keyword)

  • 作者: 灬跪求粉色木耳灬
  • 来源: 51数据库
  • 2021-10-05

c#申请一个大数组(use a large array in c#)

在c#里,有时候我需要能够申请一个很大的数组、使用之、然后立即释放其占用的内存。

sometimes i need to allocate a large array, use it and then release its memory space immediately.

由于在c#里提供的 int[] array = new int[1000000]; 这样的数组,其内存释放很难由程序员完全控制,在申请一个大数组后,程序可能会变得很慢。

if i use something like  int[] array = new int[1000000]; , it will be difficult to release its memory space by programmer and the app probably runs slower and slower.

特别是在c#+opengl编程中,我在使用vao/vbo时十分需要设计一个非托管的数组,比如在glbufferdata时我希望可以使用下面的glbufferdata:

specially in c#+opengl routines when i'm using vao/vbo, i need an unmanaged array for glbufferdata:

/// <summary>
 /// 设置当前vbo的数据。
 /// </summary>
 /// <param name="target"></param>
 /// <param name="data"></param>
 /// <param name="usage"></param>
 public static void glbufferdata(uint target, unmanagedarraybase data, uint usage)
 {
 getdelegatefor<glbufferdata>()((uint)target,
 data.bytelength, // 使用非托管数组
 data.header, // 使用非托管数组
 (uint)usage);
 }
 // ...
 // glbufferdata的声明
 private delegate void glbufferdata(uint target, int size, intptr data, uint usage);

而在指定vbo的数据时,可能是float、vec3等等类型:

and the content in vbo can be float, vec3 and any other structs.

/// <summary>
 /// 金字塔的posotion array.
 /// </summary>
 static vec3[] positions = new vec3[]
 {
 new vec3(0.0f, 1.0f, 0.0f),
 new vec3(-1.0f, -1.0f, 1.0f),
 // ...
 new vec3(-1.0f, -1.0f, 1.0f),
 };
// create a vertex buffer for the vertex data.
 {
 uint[] ids = new uint[1];
 gl.genbuffers(1, ids);
 gl.bindbuffer(gl.gl_array_buffer, ids[0]);
 // 使用vec3作为泛型的非托管数组的参数
 unmanagedarray<vec3> positionarray = new unmanagedarray<vec3>(positions.length);
 for (int i = 0; i < positions.length; i++)
 {
  // 使用this[i]这样的索引方式来读写非托管数组的元素
  positionarray[i] = positions[i];
 }
 gl.bufferdata(bufferdatatarget.arraybuffer, positionarray, bufferdatausage.staticdraw);
 gl.vertexattribpointer(positionlocation, 3, gl.gl_float, false, 0, intptr.zero);
 gl.enablevertexattribarray(positionlocation);
 }

unmanagedarray<t>

所以我设计了这样一个非托管的数组类型:无unsafe,可接收任何struct类型作为泛型参数,可随时释放内存。

so i designed this unmangedarray<t> : no 'unsafe' keyword, takes any struct as generic parameter, can be released anytime you want.

1 /// <summary>
 2 /// 元素类型为sbyte, byte, char, short, ushort, int, uint, long, ulong, float, double, decimal, bool或其它struct的非托管数组。
 3 /// <para>不能使用enum类型作为t。</para>
 4 /// </summary>
 5 /// <typeparam name="t">sbyte, byte, char, short, ushort, int, uint, long, ulong, float, double, decimal, bool或其它struct, 不能使用enum类型作为t。</typeparam>
 6 public class unmanagedarray<t> : unmanagedarraybase where t : struct
 7 {
 8 
 9 /// <summary>
 10 ///元素类型为sbyte, byte, char, short, ushort, int, uint, long, ulong, float, double, decimal, bool或其它struct的非托管数组。 
 11 /// </summary>
 12 /// <param name="count"></param>
 13 [methodimpl(methodimploptions.synchronized)]
 14 public unmanagedarray(int count)
 15 : base(count, marshal.sizeof(typeof(t)))
 16 {
 17 }
 18 
 19 /// <summary>
 20 /// 获取或设置索引为<paramref name="index"/>的元素。
 21 /// </summary>
 22 /// <param name="index"></param>
 23 /// <returns></returns>
 24 public t this[int index]
 25 {
 26 get
 27 {
 28  if (index < 0 || index >= this.count)
 29  throw new indexoutofrangeexception("index of unmanagedarray is out of range");
 30 
 31  var pitem = this.header + (index * elementsize);
 32  //var obj = marshal.ptrtostructure(pitem, typeof(t));
 33  //t result = (t)obj;
 34  t result = marshal.ptrtostructure<t>(pitem);// works in .net 4.5.1
 35  return result;
 36 }
 37 set
 38 {
 39  if (index < 0 || index >= this.count)
 40  throw new indexoutofrangeexception("index of unmanagedarray is out of range");
 41  
 42  var pitem = this.header + (index * elementsize);
 43  //marshal.structuretoptr(value, pitem, true);
 44  marshal.structuretoptr<t>(value, pitem, true);// works in .net 4.5.1
 45 }
 46 }
 47 
 48 /// <summary>
 49 /// 按索引顺序依次获取各个元素。
 50 /// </summary>
 51 /// <returns></returns>
 52 public ienumerable<t> getelements()
 53 {
 54 if (!this.disposed)
 55 {
 56  for (int i = 0; i < this.count; i++)
 57  {
 58  yield return this[i];
 59  }
 60 }
 61 }
 62 }
 63 
 64 /// <summary>
 65 /// 非托管数组的基类。
 66 /// </summary>
 67 public abstract class unmanagedarraybase : idisposable
 68 {
 69 
 70 /// <summary>
 71 /// 数组指针。
 72 /// </summary>
 73 public intptr header { get; private set; }
 74 
 75 /// <summary>
 76 /// 元素数目。
 77 /// </summary>
 78 public int count { get; private set; }
 79 
 80 /// <summary>
 81 /// 单个元素的字节数。
 82 /// </summary>
 83 protected int elementsize;
 84 
 85 /// <summary>
 86 /// 申请到的字节数。(元素数目 * 单个元素的字节数)。
 87 /// </summary>
 88 public int bytelength
 89 {
 90 get { return this.count * this.elementsize; }
 91 }
 92 
 93 
 94 /// <summary>
 95 /// 非托管数组。
 96 /// </summary>
 97 /// <param name="elementcount">元素数目。</param>
 98 /// <param name="elementsize">单个元素的字节数。</param>
 99 [methodimpl(methodimploptions.synchronized)]
100 protected unmanagedarraybase(int elementcount, int elementsize)
101 {
102 this.count = elementcount;
103 this.elementsize = elementsize;
104 
105 int memsize = elementcount * elementsize;
106 this.header = marshal.allochglobal(memsize);
107 
108 allocatedarrays.add(this);
109 }
110 
111 private static readonly list<idisposable> allocatedarrays = new list<idisposable>();
112 
113 /// <summary>
114 /// 立即释放所有<see cref="unmanagedarray"/>。
115 /// </summary>
116 [methodimpl(methodimploptions.synchronized)]
117 public static void freeall()
118 {
119 foreach (var item in allocatedarrays)
120 {
121  item.dispose();
122 }
123 allocatedarrays.clear();
124 }
125 
126 ~unmanagedarraybase()
127 {
128 dispose();
129 }
130 
131 #region idisposable members
132 
133 /// <summary>
134 /// internal variable which checks if dispose has already been called
135 /// </summary>
136 protected boolean disposed;
137 
138 /// <summary>
139 /// releases unmanaged and - optionally - managed resources
140 /// </summary>
141 /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
142 protected void dispose(boolean disposing)
143 {
144 if (disposed)
145 {
146  return;
147 }
148 
149 if (disposing)
150 {
151  //managed cleanup code here, while managed refs still valid
152 }
153 //unmanaged cleanup code here
154 intptr ptr = this.header;
155 
156 if (ptr != intptr.zero)
157 {
158  this.count = 0;
159  this.header = intptr.zero;
160  marshal.freehglobal(ptr);
161 }
162 
163 disposed = true;
164 }
165 
166 /// <summary>
167 /// performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
168 /// </summary>
169 public void dispose()
170 {
171 this.dispose(true);
172 gc.suppressfinalize(this);
173 }
174 
175 #endregion
176  
177 }

unmanagedarray

如何使用(how to use)

unmanagedarray<t>使用方式十分简单,就像一个普通的数组一样:

using unamangedaray<t> is just like a normal array(int[], vec3[], etc.):

internal static void typicalscene()
 {
 const int count = 100;

 // 测试float类型
 var floatarray = new unmanagedarray<float>(count);
 for (int i = 0; i < count; i++)
 {
 floatarray[i] = i;
 }
 for (int i = 0; i < count; i++)
 {
 var item = floatarray[i];
 if (item != i)
 { throw new exception(); }
 }

 // 测试int类型
 var intarray = new unmanagedarray<int>(count);
 for (int i = 0; i < count; i++)
 {
 intarray[i] = i;
 }
 for (int i = 0; i < count; i++)
 {
 var item = intarray[i];
 if (item != i)
 { throw new exception(); }
 }

 // 测试bool类型
 var boolarray = new unmanagedarray<bool>(count);
 for (int i = 0; i < count; i++)
 {
 boolarray[i] = i % 2 == 0;
 }
 for (int i = 0; i < count; i++)
 {
 var item = boolarray[i];
 if (item != (i % 2 == 0))
 { throw new exception(); }
 }

 // 测试vec3类型
 var vec3array = new unmanagedarray<vec3>(count);
 for (int i = 0; i < count; i++)
 {
 vec3array[i] = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2);
 }
 for (int i = 0; i < count; i++)
 {
 var item = vec3array[i];
 var old = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2);
 if (item.x != old.x || item.y != old.y || item.z != old.z)
 { throw new exception(); }
 }

 // 测试foreach
 foreach (var item in vec3array.getelements())
 {
 console.writeline(item);
 }

 // 释放此数组占用的内存,这之后就不能再使用vec3array了。
 vec3array.dispose();

 // 立即释放所有非托管数组占用的内存,这之后就不能再使用上面申请的数组了。
 unmanagedarraybase.freeall();
 }

快速读写unmanagedarray<t>

unmanagedarrayhelper

由于很多时候需要申请和使用很大的unmanagedarray<t>,直接使用this[index]索引方式速度会偏慢,所以我添加了几个辅助方法,专门解决快速读写unmanagedarray<t>的问题。

public static class unmanagedarrayhelper
 {
 ///// <summary>
 ///// 错误 1 无法获取托管类型(“t”)的地址和大小,或无法声明指向它的指针
 ///// </summary>
 ///// <typeparam name="t"></typeparam>
 ///// <param name="array"></param>
 ///// <returns></returns>
 //public static unsafe t* firstelement<t>(this unmanagedarray<t> array) where t : struct
 //{
 // var header = (void*)array.header;
 // return (t*)header;
 //}

 /// <summary>
 /// 获取非托管数组的第一个元素的地址。
 /// </summary>
 /// <param name="array"></param>
 /// <returns></returns>
 public static unsafe void* firstelement(this unmanagedarraybase array)
 {
 var header = (void*)array.header;

 return header;
 }

 public static unsafe void* lastelement(this unmanagedarraybase array)
 {
 var last = (void*)(array.header + (array.bytelength - array.bytelength / array.length));

 return last;
 }

 /// <summary>
 /// 获取非托管数组的最后一个元素的地址再向后一个单位的地址。
 /// </summary>
 /// <param name="array"></param>
 /// <returns></returns>
 public static unsafe void* tailaddress(this unmanagedarraybase array)
 {
 var tail = (void*)(array.header + array.bytelength);

 return tail;
 }
 }

如何使用

这个类型实现了3个扩展方法,可以获取unmanagedarray<t>的第一个元素的位置、最后一个元素的位置、最后一个元素+1的位置。用这种unsafe的方法可以实现c语言一样的读写速度。

下面是一个例子。用unsafe的方式读写unmanagedarray<t>,速度比this[index]方式快10到70倍。

public static void typicalscene()
 {
 int length = 1000000;
 unmanagedarray<int> array = new unmanagedarray<int>(length);
 unmanagedarray<int> array2 = new unmanagedarray<int>(length);

 long tick = datetime.now.ticks;
 for (int i = 0; i < length; i++)
 {
 array[i] = i;
 }
 long totalticks = datetime.now.ticks - tick;

 tick = datetime.now.ticks;
 unsafe
 {
 int* header = (int*)array2.firstelement();
 int* last = (int*)array2.lastelement();
 int* tailaddress = (int*)array2.tailaddress();
 int value = 0;
 for (int* ptr = header; ptr <= last/*or: ptr < tailaddress*/; ptr++)
 {
  *ptr = value++;
 }
 }
 long totalticks2 = datetime.now.ticks - tick;
 console.writeline("ticks: {0}, {1}", totalticks, totalticks2);// unsafe method works faster.

 for (int i = 0; i < length; i++)
 {
 if (array[i] != i)
 {
  console.writeline("something wrong here");
 }
 if (array2[i] != i)
 {
  console.writeline("something wrong here");
 }
 }

 array.dispose();
 array2.dispose();
 }
unsafe
 {
  vec3* header = (vec3*)vec3array.firstelement();
  vec3* last = (vec3*)vec3array.lastelement();
  vec3* tailaddress = (vec3*)vec3array.tailaddress();
  int i = 0;
  for (vec3* ptr = header; ptr <= last/*or: ptr < tailaddress*/; ptr++)
  {
  *ptr = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2);
  i++;
  }
  i = 0;
  for (vec3* ptr = header; ptr <= last/*or: ptr < tailaddress*/; ptr++, i++)
  {
  var item = *ptr;
  var old = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2);
  if (item.x != old.x || item.y != old.y || item.z != old.z)
  { throw new exception(); }
  }
 }

2015-08-25

用structlayout和marshalas支持复杂的struct

在opengl中我需要用unmanagedarray<mat4>,其中mat4定义如下:

1 /// <summary>
 2 /// represents a 4x4 matrix.
 3 /// </summary>
 4 [structlayout(layoutkind.sequential, charset=utf-8.ansi, size = 4 * 4 * 4)]
 5 public struct mat4
 6 {
 7 /// <summary>
 8 /// gets or sets the <see cref="vec4"/> column at the specified index.
 9 /// </summary>
10 /// <value>
11 /// the <see cref="vec4"/> column.
12 /// </value>
13 /// <param name="column">the column index.</param>
14 /// <returns>the column at index <paramref name="column"/>.</returns>
15 public vec4 this[int column]
16 {
17 get { return cols[column]; }
18 set { cols[column] = value; }
19 }
20 
21 /// <summary>
22 /// gets or sets the element at <paramref name="column"/> and <paramref name="row"/>.
23 /// </summary>
24 /// <value>
25 /// the element at <paramref name="column"/> and <paramref name="row"/>.
26 /// </value>
27 /// <param name="column">the column index.</param>
28 /// <param name="row">the row index.</param>
29 /// <returns>
30 /// the element at <paramref name="column"/> and <paramref name="row"/>.
31 /// </returns>
32 public float this[int column, int row]
33 {
34 get { return cols[column][row]; }
35 set { cols[column][row] = value; }
36 }
37 
38 /// <summary>
39 /// the columms of the matrix.
40 /// </summary>
41 [marshalas(unmanagedtype.byvalarray, sizeconst = 4)]
42 private vec4[] cols;
43 }
44 
45 /// <summary>
46 /// represents a four dimensional vector.
47 /// </summary>
48 [structlayout(layoutkind.sequential, charset=utf-8.ansi, size = 4 * 4)]
49 public struct vec4
50 {
51 public float x;
52 public float y;
53 public float z;
54 public float w;
55 
56 public float this[int index]
57 {
58 get
59 {
60  if (index == 0) return x;
61  else if (index == 1) return y;
62  else if (index == 2) return z;
63  else if (index == 3) return w;
64  else throw new exception("out of range.");
65 }
66 set
67 {
68  if (index == 0) x = value;
69  else if (index == 1) y = value;
70  else if (index == 2) z = value;
71  else if (index == 3) w = value;
72  else throw new exception("out of range.");
73 }
74 }
75 }

mat4

注意:unmanagedarray<t>支持的struct,t的大小必须是确定的。所以在mat4里我们用 [structlayout(layoutkind.sequential, charset=utf-8.ansi, size = 4 * 4 * 4)] 指定mat4的大小为4个 vec4 * 4个 float * 4个字节(每个float) = 64字节,并且在 private vec4[] cols; 上用 [marshalas(unmanagedtype.byvalarray, sizeconst = 4)] 规定了cols的元素数必须是4。之后在 vec4 上的 [structlayout(layoutkind.sequential, charset=utf-8.ansi, size = 4 * 4)] 不写也可以,因为vec4只有4个简单的float字段,不含复杂类型。

下面是测试用例。

mat4 matrix = glm.scale(mat4.identity(), new vec3(2, 3, 4));

 var size = marshal.sizeof(typeof(mat4));
 size = marshal.sizeof(matrix);

 unmanagedarray<mat4> array = new unmanagedarray<mat4>(1);
 array[0] = matrix;

 mat4 newmatirx = array[0]; // newmatrix should be equal to matrix

 array.dispose();

如果matrix和newmatrix相等,就说明上述attribute配置正确了。

总结

到此这篇关于c#+无unsafe的非托管大数组(large unmanaged array in c# without 'unsafe' keyword)的文章就介绍到这了,更多相关c#+无unsafe的非托管大数组内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

软件
前端设计
程序设计
Java相关