JA CSharp Keyword fixed - LIHACHTETAN/ClassicUO-Bad-Newbie-CSharp-Scripts-IDE GitHub Wiki
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
C#: fixed
ブロックの存続期間中、ポインタを介して作業できるように管理データが移動不能に保たれます。固定バッファ — 構造体フィールドの個別の宣言。
簡単な例 (Example.cs)
この例を Example.cs として別に保存し、このページの他の例とは独立して実行してください。
Example.cs:
// PROJECT-EXAMPLE
int[] values = [3];
unsafe
{
fixed (int* pointer = values) *pointer = 7;
}
System.Console.WriteLine(values[0]);
プロジェクトで <AllowUnsafeBlocks>true</AllowUnsafeBlocks> を有効にしてください。ポインターは示されたスコープ内でのみ有効です。
結果:
7
構文
fixed (Type* pointer = managedValue) { ... }
.csprojでは、trueを設定します。マネージド データの場合は、通常、生のポインターを使用せずに Span を使用する方が簡単です。
例 1: 基本形式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public static class Program
{
public static async Task Main(string[] args)
{
string text = "ore";
unsafe { fixed (char* pointer = text) Console.WriteLine(*pointer); }
}
}
例 2: 別の実用的な形式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public static class Program
{
public static async Task Main(string[] args)
{
int[] values = [2, 4, 6];
unsafe { fixed (int* pointer = values) { pointer[1] = 9; Console.WriteLine(*(pointer + 1)); Console.WriteLine(sizeof(long)); } }
Console.WriteLine(values[1]);
}
}
例 3
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public static class Program
{
public static async Task Main(string[] args)
{
unsafe { Packet packet = default; packet.Bytes[0] = 7; Console.WriteLine(packet.Bytes[0]); }
}
}
public unsafe struct Packet { public fixed byte Bytes[4]; }
公式ソース: Microsoft Learn。