- Aug
- 2,808
- 144
I've been learning about how to use pointers in .NET code.
Using pointers (part of standard C) in .NET code is known as unsafe code.
Unsafe code in C# allows direct memory manipulation using pointers,
which bypasses the .NET garbage collector's safety mechanisms.
To compile unsafe code,
you need to enable unsafe context compilation with an extra compiler switch.
Here's a test command,
that I have called UNSAFE,
added to a TCC .NET plugin;
I had to add the -p:AllowUnsafeBlocks=true switch to the compiler command line;
I could have instead added the following to my jlcUtils.csproj file;
Here's the output after running jlcutils$unsafe
Posting for my future reference,
but others may also be interested.
Joe
Using pointers (part of standard C) in .NET code is known as unsafe code.
Unsafe code in C# allows direct memory manipulation using pointers,
which bypasses the .NET garbage collector's safety mechanisms.
To compile unsafe code,
you need to enable unsafe context compilation with an extra compiler switch.
Here's a test command,
that I have called UNSAFE,
added to a TCC .NET plugin;
Code:
public unsafe int UNSAFE(StringBuilder args)
{
int number = 42;
int* ptr = &number;
Console.WriteLine("Value: " + number);
Console.WriteLine("Address: " + (long)ptr);
Console.WriteLine("Value via pointer: " + *ptr);
*ptr = 100;
Console.WriteLine("New value: " + number);
return 1;
}
I had to add the -p:AllowUnsafeBlocks=true switch to the compiler command line;
Code:
dotnet build jlcUtils.csproj -c Release -p:PlatformTarget=x64 -p:AllowUnsafeBlocks=true --no-restore -v:diag
I could have instead added the following to my jlcUtils.csproj file;
Code:
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
Here's the output after running jlcutils$unsafe
Code:
Beginning test for UNSAFE
Value: 42
Address: 819496269996
Value via pointer: 42
New value: 100
Posting for my future reference,
but others may also be interested.
Joe