Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace ManagedVsUnmanagedCodeInCSharp
{
public static class GenerationInspector
{
public static int GetArrayGeneration(int sizeInBytes)
{
var array = new byte[sizeInBytes];

return GC.GetGeneration(array);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.Runtime.InteropServices;
using System.Runtime.Versioning;

namespace ManagedVsUnmanagedCodeInCSharp
{
public static partial class NativeMethods
{
[LibraryImport("user32.dll", EntryPoint = "MessageBoxW", StringMarshalling = StringMarshalling.Utf16)]
[SupportedOSPlatform("windows")]
public static partial int MessageBox(IntPtr hWnd, string text, string caption, int options);
}
}
Original file line number Diff line number Diff line change
@@ -1,94 +1,79 @@
using System.Runtime.InteropServices;
using System.Text;
using ManagedVsUnmanagedCodeInCSharp;

namespace ManagedVsUnmanagedCodeInCSharp
{
public class Program
{
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, string text, string caption, int options);

static void Main(string[] args)
{
//Unmanaged Code

MessageBox(IntPtr.Zero, "Hello, World!", "Message", 0);

var numbers = new int[] { 1, 2, 3, 4, 5 };
// Unmanaged code

unsafe
{
fixed (int* ptr = numbers)
{
for (var i = 0; i < 5; i++)
{
Console.WriteLine(*(ptr + i));
}
}
}

var bufferSize = 1024;
IntPtr buffer = UnmanagedMemoryManager.AllocateUnmanagedMemory(bufferSize);

var dataToWrite = new byte[] { 1, 2, 3, 4 };
UnmanagedMemoryManager.WriteDataToUnmanagedMemory(buffer, dataToWrite);

var readData = UnmanagedMemoryManager.ReadDataFromUnmanagedMemory(buffer, dataToWrite.Length);

Console.WriteLine("Data read from unmanaged memory:");
foreach (byte value in readData)
{
Console.Write(value + " ");
}
Console.WriteLine();
if (OperatingSystem.IsWindows())
{
NativeMethods.MessageBox(IntPtr.Zero, "Hello, World!", "Message", 0);
}

UnmanagedMemoryManager.FreeUnmanagedMemory(buffer);
var numbers = new int[] { 1, 2, 3, 4, 5 };

// Marshaling a string from managed to unmanaged code
var input = "Purple Jackets";
IntPtr unmanagedString = Marshal.StringToHGlobalAnsi(input);
unsafe
{
fixed (int* ptr = numbers)
{
for (var i = 0; i < numbers.Length; i++)
{
Console.WriteLine(*(ptr + i));
}
}
}

Marshal.FreeHGlobal(unmanagedString);
var bufferSize = 1024;
IntPtr buffer = UnmanagedMemoryManager.AllocateUnmanagedMemory(bufferSize);

//Managed Code
try
{
var dataToWrite = new byte[] { 1, 2, 3, 4 };
UnmanagedMemoryManager.WriteDataToUnmanagedMemory(buffer, dataToWrite);

var memoryManager = new ManagedMemoryManager();
var readData = UnmanagedMemoryManager.ReadDataFromUnmanagedMemory(buffer, dataToWrite.Length);

var memoryBeforeAllocation = GC.GetTotalMemory(false);
memoryManager.AllocateMemory();
var memoryAfterAllocation = GC.GetTotalMemory(false);
Console.WriteLine("Data read from unmanaged memory:");
Console.WriteLine(string.Join(" ", readData));
}
finally
{
UnmanagedMemoryManager.FreeUnmanagedMemory(buffer);
}

Console.WriteLine($"Memory Allocated to the list: {memoryAfterAllocation - memoryBeforeAllocation} bytes");
using (var unmanagedBuffer = new UnmanagedBuffer(bufferSize))
{
Marshal.WriteByte(unmanagedBuffer.DangerousGetHandle(), 42);
Console.WriteLine($"First byte of the SafeHandle buffer: {Marshal.ReadByte(unmanagedBuffer.DangerousGetHandle())}");
}

//Showcasing Best Practices
// Marshaling a string from managed to unmanaged code
var input = "Purple Jackets";
IntPtr unmanagedString = Marshal.StringToHGlobalAnsi(input);

// Bad practice: creating unnecessary objects
var memoryBeforeConcat = GC.GetTotalMemory(false);
var str = string.Empty;
try
{
Console.WriteLine(Marshal.PtrToStringAnsi(unmanagedString));
}
finally
{
Marshal.FreeHGlobal(unmanagedString);
}

for (var i = 0; i < 100000; i++)
{
str += i.ToString();
}
Console.WriteLine($"Size of ToyCarInfo in unmanaged memory: {Marshal.SizeOf<ToyCarInfo>()} bytes");

var memoryAfterConcat = GC.GetTotalMemory(false);
// Managed code

Console.WriteLine($"Memory used by string concatenation: {memoryAfterConcat - memoryBeforeConcat} bytes");
var memoryManager = new ManagedMemoryManager();

var memoryBeforeAllocation = GC.GetTotalMemory(false);
memoryManager.AllocateMemory();
var memoryAfterAllocation = GC.GetTotalMemory(false);

// Good practice: avoiding unnecessary objects
var memoryBeforeStringBuilder = GC.GetTotalMemory(false);
var sb = new StringBuilder();
Console.WriteLine($"Memory Allocated to the list: {memoryAfterAllocation - memoryBeforeAllocation} bytes");

for (var i = 0; i < 100000; i++)
{
sb.Append(i);
}
Console.WriteLine($"1,000-byte array is in generation {GenerationInspector.GetArrayGeneration(1_000)}");
Console.WriteLine($"100,000-byte array is in generation {GenerationInspector.GetArrayGeneration(100_000)}");

var result = sb.ToString();
var memoryAfterStringBuilder = GC.GetTotalMemory(false);
// Showcasing best practices

Console.WriteLine($"Memory used by StringBuilder: {memoryAfterStringBuilder - memoryBeforeStringBuilder} bytes");
}
}
}
Console.WriteLine($"Memory allocated by string concatenation: {StringBuildingAllocations.MeasureConcatenation(10_000)} bytes");
Console.WriteLine($"Memory allocated by StringBuilder: {StringBuildingAllocations.MeasureStringBuilder(10_000)} bytes");
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System.Text;

namespace ManagedVsUnmanagedCodeInCSharp
{
public static class StringBuildingAllocations
{
public static long MeasureConcatenation(int count)
{
var allocatedBefore = GC.GetAllocatedBytesForCurrentThread();

var str = string.Empty;
for (var i = 0; i < count; i++)
{
str += i.ToString();
}

return GC.GetAllocatedBytesForCurrentThread() - allocatedBefore;
}

public static long MeasureStringBuilder(int count)
{
var allocatedBefore = GC.GetAllocatedBytesForCurrentThread();

var sb = new StringBuilder();
for (var i = 0; i < count; i++)
{
sb.Append(i);
}
var result = sb.ToString();

return GC.GetAllocatedBytesForCurrentThread() - allocatedBefore;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace ManagedVsUnmanagedCodeInCSharp
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct ToyCarInfo
public struct ToyCarInfo
{
public byte Color;
public int ModelNumber;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.Runtime.InteropServices;

namespace ManagedVsUnmanagedCodeInCSharp
{
public sealed class UnmanagedBuffer : SafeHandle
{
public UnmanagedBuffer(int size) : base(IntPtr.Zero, ownsHandle: true)
{
SetHandle(Marshal.AllocHGlobal(size));
}

public override bool IsInvalid => handle == IntPtr.Zero;

protected override bool ReleaseHandle()
{
Marshal.FreeHGlobal(handle);

return true;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Runtime.InteropServices;
using ManagedVsUnmanagedCodeInCSharp;

namespace Tests
Expand All @@ -16,14 +17,80 @@ public void GivenManagedResource_WhenAllocatingMemory_ThenSucceed()
}

[Fact]
public void GivenUnmangedResource_WhenAllocatingMemory_ThenSucceed()
public void GivenUnmanagedResource_WhenAllocatingMemory_ThenSucceed()
{
var size = 1024;
var ptr = UnmanagedMemoryManager.AllocateUnmanagedMemory(size);

Assert.NotEqual(IntPtr.Zero, ptr);
try
{
Assert.NotEqual(IntPtr.Zero, ptr);
}
finally
{
UnmanagedMemoryManager.FreeUnmanagedMemory(ptr);
}
}

[Fact]
public void GivenLargeArray_WhenAllocated_ThenItIsInTheOldestGeneration()
{
var generation = GenerationInspector.GetArrayGeneration(100_000);

Assert.Equal(GC.MaxGeneration, generation);
}

[Fact]
public void GivenSmallArray_WhenAllocated_ThenItIsInAYoungerGeneration()
{
var generation = GenerationInspector.GetArrayGeneration(1_000);

Assert.True(generation < GC.MaxGeneration);
}

[Fact]
public void GivenUnmanagedBuffer_WhenDisposed_ThenHandleIsClosed()
{
var buffer = new UnmanagedBuffer(1024);
Marshal.WriteByte(buffer.DangerousGetHandle(), 42);

Assert.Equal(42, Marshal.ReadByte(buffer.DangerousGetHandle()));

buffer.Dispose();

Assert.True(buffer.IsClosed);
}

[Fact]
public void GivenStringBuilding_WhenMeasured_ThenConcatenationAllocatesMore()
{
var concatenation = StringBuildingAllocations.MeasureConcatenation(10_000);
var stringBuilder = StringBuildingAllocations.MeasureStringBuilder(10_000);

Assert.True(concatenation > stringBuilder * 10);
}

[Fact]
public void GivenToyCarInfo_WhenPackedToOneByte_ThenItHasNoPadding()
{
Assert.Equal(9, Marshal.SizeOf<ToyCarInfo>());
}

[Fact]
public void GivenFileWriter_WhenDataIsWritten_ThenFileHoldsIt()
{
var fileName = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.txt");

try
{
FileWriter.WriteDataToFile(fileName, "Purple Jackets");

UnmanagedMemoryManager.FreeUnmanagedMemory(ptr);
Assert.Equal("Purple Jackets", File.ReadAllText(fileName));
}
finally
{
File.Delete(fileName);
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

Expand All @@ -11,13 +11,13 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.2.0">
<PackageReference Include="coverlet.collector" Version="10.1.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
Expand Down
Loading