Repository navigation
Expand file tree
/
Copy pathTestPyBuffer.cs
More file actions
236 lines (190 loc) · 7.58 KB
/
Copy pathTestPyBuffer.cs
File metadata and controls
236 lines (190 loc) · 7.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
using System;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using NUnit.Framework;
using Python.Runtime;
using Python.Runtime.Codecs;
namespace Python.EmbeddingTest
{
class TestPyBuffer
{
[OneTimeSetUp]
public void SetUp()
{
TupleCodec<ValueTuple>.Register();
}
[OneTimeTearDown]
public void Dispose()
{
PyObjectConversions.Reset();
}
[Test]
public void TestBufferWrite()
{
string bufferTestString = "hello world! !$%&/()=?";
string bufferTestString2 = "h llo world! !$%&/()=?";
using var _ = Py.GIL();
using var pythonArray = ByteArrayFromAsciiString(bufferTestString);
using (PyBuffer buf = pythonArray.GetBuffer(PyBUF.WRITABLE))
{
byte[] managedArray = { (byte)' ' };
buf.Write(managedArray, 0, managedArray.Length, 1);
}
string result = pythonArray.InvokeMethod("decode", "utf-8".ToPython()).As<string>();
Assert.That(result == bufferTestString2, Is.True);
}
[Test]
public void TestBufferRead()
{
string bufferTestString = "hello world! !$%&/()=?";
using var _ = Py.GIL();
using var pythonArray = ByteArrayFromAsciiString(bufferTestString);
byte[] managedArray = new byte[bufferTestString.Length];
using (PyBuffer buf = pythonArray.GetBuffer())
{
managedArray[0] = (byte)' ';
buf.Read(managedArray, 1, managedArray.Length - 1, 1);
}
string result = new UTF8Encoding().GetString(managedArray);
Assert.That(result, Is.EqualTo($" {bufferTestString.Substring(1)}"));
}
[Test]
public void GetPointer()
{
// create 3D NumPy array
int[] shape = [10, 10, 10];
using PyObject ndArray = np.zeros(shape);
using PyBuffer buf = ndArray.GetBuffer(PyBUF.STRIDES);
var ptr = buf.GetPointer([0, 0, 0]);
Assert.That(ptr, Is.Not.EqualTo(IntPtr.Zero));
var ptrEnd = buf.GetPointer([9, 9, 9]);
Assert.That(ptrEnd, Is.Not.EqualTo(IntPtr.Zero));
Assert.Throws<ArgumentNullException>(() => buf.GetPointer(null!));
Assert.Throws<ArgumentOutOfRangeException>(() => buf.GetPointer([0, 0]));
Assert.Throws<ArgumentOutOfRangeException>(() => buf.GetPointer([0, 0, 0, 0]));
Assert.Throws<ArgumentOutOfRangeException>(() => buf.GetPointer([-1, 0, 0]));
Assert.Throws<ArgumentOutOfRangeException>(() => buf.GetPointer([0, -1, 0]));
Assert.Throws<ArgumentOutOfRangeException>(() => buf.GetPointer([0, 0, -1]));
Assert.Throws<ArgumentOutOfRangeException>(() => buf.GetPointer([10, 0, 0]));
Assert.Throws<ArgumentOutOfRangeException>(() => buf.GetPointer([0, 10, 0]));
Assert.Throws<ArgumentOutOfRangeException>(() => buf.GetPointer([0, 0, 10]));
using PyBuffer buf2 = ndArray.GetBuffer(PyBUF.ND);
Assert.Throws<InvalidOperationException>(
() => buf2.GetPointer([0, 0, 0])
);
}
[Test]
public void ArrayHasBuffer()
{
var array = new[,] { { 1, 2 }, { 3, 4 } };
var memoryView = PythonEngine.Eval("memoryview");
var mem = memoryView.Invoke(array.ToPython());
Assert.That(mem[(0, 0).ToPython()].As<int>(), Is.EqualTo(1));
Assert.That(mem[(1, 0).ToPython()].As<int>(), Is.EqualTo(array[1, 0]));
}
[Test]
public void RefCount()
{
using var _ = Py.GIL();
using var arr = ByteArrayFromAsciiString("hello world! !$%&/()=?");
Assert.That(arr.Refcount, Is.EqualTo(1));
using (PyBuffer buf = arr.GetBuffer())
{
Assert.That(arr.Refcount, Is.EqualTo(2));
}
Assert.That(arr.Refcount, Is.EqualTo(1));
}
[Test]
public void Finalization()
{
if (Type.GetType("Mono.Runtime") is not null)
{
Assert.Inconclusive("test unreliable in Mono");
return;
}
using var _ = Py.GIL();
using var arr = ByteArrayFromAsciiString("hello world! !$%&/()=?");
Assert.That(arr.Refcount, Is.EqualTo(1));
MakeBufAndLeak(arr);
GC.Collect();
GC.WaitForPendingFinalizers();
Finalizer.Instance.Collect();
Assert.That(arr.Refcount, Is.EqualTo(1));
}
[Test]
public void MultidimensionalNumPyArray()
{
var ndarray = np.arange(24).reshape(1, 2, 3, 4).T;
PyObject ndim = ndarray.ndim;
PyObject shape = ndarray.shape;
PyObject strides = ndarray.strides;
PyObject contiguous = ndarray.flags["C_CONTIGUOUS"];
using PyBuffer buf = ndarray.GetBuffer(PyBUF.STRIDED);
Assert.Multiple(() =>
{
Assert.That(buf.Dimensions, Is.EqualTo(ndim.As<int>()));
Assert.That(buf.Shape, Is.EqualTo(shape.As<long[]>()));
Assert.That(buf.Strides, Is.EqualTo(strides.As<long[]>()));
Assert.That(buf.IsContiguous(BufferOrderStyle.C), Is.EqualTo(contiguous.As<bool>()));
});
}
[Test]
public void ConcurrentDispose()
{
// Two threads racing on Dispose() must not double-release the view —
// Interlocked.Exchange on disposedValue gates PyBuffer_Release.
// Smoke test: no crash, exception, or buffer-protocol violation.
using var _ = Py.GIL();
using var arr = ByteArrayFromAsciiString("hello world! !$%&/()=?");
const int iterations = 200;
for (int i = 0; i < iterations; i++)
{
PyBuffer buf = arr.GetBuffer();
IntPtr ts = PythonEngine.BeginAllowThreads();
using var barrier = new Barrier(2);
Exception captured = null;
Action race = () =>
{
try
{
barrier.SignalAndWait();
using (Py.GIL()) buf.Dispose();
}
catch (Exception ex) { Interlocked.CompareExchange(ref captured, ex, null); }
};
var t1 = new Thread(() => race());
var t2 = new Thread(() => race());
t1.Start(); t2.Start();
t1.Join(); t2.Join();
PythonEngine.EndAllowThreads(ts);
if (captured != null) throw captured;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void MakeBufAndLeak(PyObject bufProvider)
{
PyBuffer buf = bufProvider.GetBuffer();
}
static PyObject ByteArrayFromAsciiString(string str)
{
using var scope = Py.CreateScope();
return Runtime.Runtime.PyByteArray_FromStringAndSize(str).MoveToPyObject();
}
dynamic np
{
get
{
try
{
return Py.Import("numpy");
}
catch (PythonException)
{
Assert.Inconclusive("Numpy or dependency not installed");
return null;
}
}
}
}
}