Tanoda
StructMarshalTests.cs
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (C) Ultraleap, Inc. 2011-2020. *
3 * *
4 * Use subject to the terms of the Apache License 2.0 available at *
5 * http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
6 * between Ultraleap and you, your company or other organization. *
7 ******************************************************************************/
8
9using System;
10using System.Runtime.InteropServices;
11using NUnit.Framework;
12using LeapInternal;
13
14namespace Leap.LeapCSharp.Tests {
15
16 [StructLayout(LayoutKind.Sequential)]
18 public int id;
19 public TestMarshaledStruct(int t) { id = t; }
20 }
21
22 [TestFixture()]
23 public class StructMarshalTests {
24 public const int ARRAY_SIZE = 5;
25 public const int ARRAY_TEST_INDEX = 3;
26 public const int TEST_ID = 23;
27
28 private int _size;
29 private IntPtr _ptr;
30 private TestMarshaledStruct _testStruct;
31
32 [SetUp]
33 public void Setup() {
34 _size = Marshal.SizeOf(typeof(TestMarshaledStruct));
35 //For each test, allocate a chunk of memory large enough for [ARRAY_SIZE] structs
36 _ptr = Marshal.AllocHGlobal(_size * ARRAY_SIZE);
37 _testStruct = new TestMarshaledStruct(TEST_ID);
38 }
39
40 [TearDown]
41 public void Teardown() {
42 _size = 0;
43 Marshal.FreeHGlobal(_ptr);
44 _ptr = IntPtr.Zero;
45 _testStruct = new TestMarshaledStruct();
46 }
47
48 [Test]
49 public void SizeTest() {
50 int reportedSize = StructMarshal<TestMarshaledStruct>.Size;
51 Assert.That(_size, Is.EqualTo(reportedSize), "Size must match Marshal.SizeOf.");
52 }
53
54 [Test]
55 public void PtrToStructTest() {
56 Marshal.StructureToPtr(_testStruct, _ptr, false);
57
59 StructMarshal<TestMarshaledStruct>.PtrToStruct(_ptr, out output);
60 Assert.That(_testStruct.id, Is.EqualTo(output.id), "Input must match output.");
61 }
62
63 [Test]
65 Marshal.StructureToPtr(_testStruct, (IntPtr)((long)_ptr + _size * ARRAY_TEST_INDEX), false);
66
68 StructMarshal<TestMarshaledStruct>.ArrayElementToStruct(_ptr, ARRAY_TEST_INDEX, out output);
69 Assert.That(_testStruct.id, Is.EqualTo(output.id), "Input must match output.");
70 }
71 }
72}