Skip to content

Commit 7ada240

Browse files
author
hardcoded
committed
Improved PyLong so it actually supports int64.
1 parent edeb85f commit 7ada240

2 files changed

Lines changed: 74 additions & 1 deletion

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
using System;
2+
using NUnit.Framework;
3+
using Python.Runtime;
4+
5+
namespace Python.EmbeddingTest
6+
{
7+
[TestFixture]
8+
public class PyLongTest
9+
{
10+
private IntPtr gs;
11+
12+
[SetUp]
13+
public void SetUp()
14+
{
15+
PythonEngine.Initialize();
16+
gs = PythonEngine.AcquireLock();
17+
}
18+
19+
[TearDown]
20+
public void TearDown()
21+
{
22+
PythonEngine.ReleaseLock(gs);
23+
PythonEngine.Shutdown();
24+
}
25+
26+
[Test]
27+
public void TestToInt64()
28+
{
29+
long largeNumber = 8L * 1024L * 1024L * 1024L; // 8 GB
30+
PyLong pyLargeNumber = new PyLong(largeNumber);
31+
Assert.AreEqual(largeNumber, pyLargeNumber.ToInt64());
32+
}
33+
}
34+
}

pythonnet/src/runtime/pylong.cs

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ public PyLong(uint value) : base() {
9292
/// </remarks>
9393

9494
public PyLong(long value) : base() {
95-
obj = Runtime.PyLong_FromLong(value);
95+
obj = Runtime.PyLong_FromLongLong(value);
9696
if (obj == IntPtr.Zero) {
9797
throw new PythonException();
9898
}
@@ -246,7 +246,46 @@ public static PyLong AsLong(PyObject value) {
246246
return new PyLong(op);
247247
}
248248

249+
/// <summary>
250+
/// ToInt16 Method
251+
/// </summary>
252+
///
253+
/// <remarks>
254+
/// Return the value of the Python long object as an int16.
255+
/// </remarks>
256+
257+
public short ToInt16()
258+
{
259+
return System.Convert.ToInt16(this.ToInt64());
260+
}
261+
262+
263+
/// <summary>
264+
/// ToInt32 Method
265+
/// </summary>
266+
///
267+
/// <remarks>
268+
/// Return the value of the Python long object as an int32.
269+
/// </remarks>
270+
271+
public int ToInt32()
272+
{
273+
return System.Convert.ToInt32(this.ToInt64());
274+
}
275+
276+
277+
/// <summary>
278+
/// ToInt64 Method
279+
/// </summary>
280+
///
281+
/// <remarks>
282+
/// Return the value of the Python long object as an int64.
283+
/// </remarks>
249284

285+
public long ToInt64()
286+
{
287+
return Runtime.PyLong_AsLongLong(obj);
288+
}
250289
}
251290

252291
}

0 commit comments

Comments
 (0)