├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── UnsafeHelper.IL ├── IL.il └── UnsafeHelper.IL.ilproj ├── UnsafeHelper.Test ├── Program.cs └── UnsafeHelper.Test.csproj ├── UnsafeHelper.UnitTest ├── UnsafeHelper.UnitTest.csproj └── UnsafeTest.cs ├── UnsafeHelper.sln ├── UnsafeHelper ├── ManagedObject.cs ├── MethodTable.cs ├── Properties │ └── launchSettings.json ├── StructExtension.cs ├── UnsafeHelper.cs └── UnsafeHelper.csproj └── global.json /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd 364 | /Test 365 | /InPlaceRuntimeTest 366 | /InternalUnsafe 367 | /FrameworkTest 368 | /UnsafeBenchmark 369 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 ilyfairy 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # UnsafeHelper 2 | 3 | 提供一些不安全方法 4 | 有些代码参考了dotnet的源码 5 | 6 | ## 编译 7 | 请使用Visual Studio 2022(v17.4+)进行编译 8 | 9 | ## 注意事项 10 | 调用之前请先测试,可能会导致程序异常 11 | 一些方法的命名可能会经常发生改变 12 | 不能保证AOT后能够正常运行,可能会遇到致命错误 -------------------------------------------------------------------------------- /UnsafeHelper.IL/IL.il: -------------------------------------------------------------------------------- 1 | .assembly extern mscorlib 2 | { } 3 | 4 | .assembly UnsafeHelper.IL 5 | { 6 | .ver 1:0:0:0 7 | } 8 | 9 | .module UnsafeHelper.IL.dll 10 | 11 | .class public abstract auto ansi sealed beforefieldinit IlyfairyLib.Unsafe.Internal.IL 12 | { 13 | .method public hidebysig static void* GetMethodTable(object obj) cil managed aggressiveinlining 14 | { 15 | .maxstack 8 16 | ldarg.0 17 | ret 18 | } 19 | 20 | .method public hidebysig static uint8& GetMethodTableReference(object obj) cil managed aggressiveinlining 21 | { 22 | .maxstack 2 23 | ldarg.0 24 | ldind.i 25 | ret 26 | } 27 | 28 | .method public hidebysig static !!T As(native int objectAddress) cil managed aggressiveinlining 29 | { 30 | .maxstack 2 31 | ldarg.0 32 | ret 33 | } 34 | 35 | .method public hidebysig static !!T As(void* objectAddress) cil managed aggressiveinlining 36 | { 37 | .maxstack 2 38 | ldarg.0 39 | ret 40 | } 41 | } -------------------------------------------------------------------------------- /UnsafeHelper.IL/UnsafeHelper.IL.ilproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | netstandard2.0 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /UnsafeHelper.Test/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using IlyfairyLib.Unsafe; 3 | 4 | namespace UnsafeHelper.Test 5 | { 6 | internal class Program 7 | { 8 | static void Main(string[] args) 9 | { 10 | Console.WriteLine("Hello World!"); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /UnsafeHelper.Test/UnsafeHelper.Test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net7.0 6 | x86 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /UnsafeHelper.UnitTest/UnsafeHelper.UnitTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | true 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | all 15 | 16 | 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | all 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /UnsafeHelper.UnitTest/UnsafeTest.cs: -------------------------------------------------------------------------------- 1 | using IlyfairyLib.Unsafe; 2 | using System; 3 | using System.Diagnostics; 4 | using System.Runtime.CompilerServices; 5 | using System.Runtime.InteropServices; 6 | using Xunit; 7 | 8 | #pragma warning disable CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type 9 | namespace UnsafeHelperTest 10 | { 11 | public unsafe class UnsafeTest 12 | { 13 | [Fact] 14 | public void GetRefPointer() 15 | { 16 | int num = 1; 17 | void* p1 = (void*)UnsafeHelper.GetPointer(ref num); 18 | void* p2 = # 19 | Assert.True(p1 == p2); 20 | } 21 | 22 | [Fact] 23 | public void GetObjectPointer() 24 | { 25 | object obj = new object(); 26 | var p1 = *(void**)&obj; 27 | var p2 = UnsafeHelper.GetPointer(obj); 28 | Assert.True(p1 == p2); 29 | } 30 | 31 | [Fact] 32 | public void GetObjectMethodTable() 33 | { 34 | object obj = new object(); 35 | var p1 = (void*)UnsafeHelper.GetMethodTablePointer(obj); 36 | var p2 = (void*)typeof(object).TypeHandle.Value; 37 | Assert.True(p1 == p2); 38 | } 39 | 40 | [Fact] 41 | public void GetObjectRawDataPointer() 42 | { 43 | IntClass ic = new IntClass 44 | { 45 | A = 0x123456 46 | }; 47 | var a = *(int*)UnsafeHelper.GetRawDataPointer(ic); 48 | Assert.True(a == 0x123456); 49 | } 50 | 51 | [Fact] 52 | public void CopyParentToChild() 53 | { 54 | ParentClass parent = new(); 55 | parent.A = "val1"; 56 | ChildClass child = new(); 57 | child.B = "val2"; 58 | UnsafeHelper.CopyParentToChild(parent, child); 59 | Assert.True(parent.A == child.A); 60 | Assert.True(child.B == "val2"); 61 | } 62 | 63 | [Fact] 64 | public void CopyChildToParent() 65 | { 66 | ChildClass child = new(); 67 | child.A = "val1"; 68 | ParentClass parent = new(); 69 | UnsafeHelper.CopyChildToParent(child, parent); 70 | Assert.True(parent.A == child.A); 71 | } 72 | 73 | [Fact] 74 | public void ArrayElementSize() 75 | { 76 | var arr1 = new string[] { "str" }; 77 | var arr2 = new decimal[] { 1m }; 78 | Assert.True(UnsafeHelper.GetArrayItemSize(arr1) == IntPtr.Size); 79 | Assert.True(UnsafeHelper.GetArrayItemSize(arr2) == sizeof(decimal)); 80 | } 81 | 82 | [Fact] 83 | public void StringAsSpan() 84 | { 85 | string qwq = " str"[1..]; 86 | Assert.True(UnsafeHelper.AsSpan(qwq).SequenceEqual(qwq)); 87 | } 88 | 89 | [Fact] 90 | public void ChangeObjectHandle() 91 | { 92 | string a = " str"[1..]; 93 | Assert.True(UnsafeHelper.ChangeObjectHandle(a, typeof(long)).GetType() == typeof(long)); 94 | Assert.True(UnsafeHelper.ChangeObjectHandle(a).GetType() == typeof(object)); 95 | } 96 | 97 | [Fact] 98 | public void AllocObject() 99 | { 100 | var obj = UnsafeHelper.AllocObject(typeof(long), (UIntPtr)8); 101 | Assert.True(obj != null); 102 | var str = obj.ToString(); 103 | Assert.True(str == "0"); 104 | UnsafeHelper.FreeObject(obj); 105 | } 106 | 107 | [Fact] 108 | public void FieldOffset() 109 | { 110 | var offset = UnsafeHelper.GetFieldOffset(typeof(Foo), "C"); 111 | Assert.True(offset == 8); 112 | } 113 | 114 | [Fact] 115 | public void ObjectSize() 116 | { 117 | Assert.True(UnsafeHelper.GetStructSize() == 24); 118 | Assert.True(UnsafeHelper.GetRawDataSize(new int[] { 1, 2 }) == (nuint)(sizeof(nint) + 8)); 119 | Assert.True(UnsafeHelper.GetRawDataSize() == (nuint)(IntPtr.Size * 2)); 120 | } 121 | 122 | [Fact] 123 | public void ArrayAsSpan() 124 | { 125 | var arr = new int[10, 10, 10, 10, 2]; 126 | ref int end = ref arr[9, 9, 9, 9, 1]; 127 | end = 123; 128 | var span = UnsafeHelper.AsSpan(arr); 129 | Assert.True(arr.Length == span.Length); 130 | Assert.True(span[^1] == end); 131 | } 132 | } 133 | 134 | 135 | [StructLayout(LayoutKind.Sequential)] 136 | internal struct Foo //24字节 137 | { 138 | public int A; //offset:0 139 | public int B; //offset:4 140 | public long C; //offset:8 141 | public long D; //offset:16 142 | } 143 | internal class ParentClass //nint字节 144 | { 145 | public string A; //offset:0 146 | } 147 | internal class ChildClass : ParentClass //nint*2字节 148 | { 149 | public string B; //offset:nint 150 | } 151 | internal class IntClass 152 | { 153 | public int A; 154 | } 155 | } 156 | #pragma warning restore CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type 157 | -------------------------------------------------------------------------------- /UnsafeHelper.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.3.32728.150 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnsafeHelper", "UnsafeHelper\UnsafeHelper.csproj", "{3E812CB3-589E-442E-8806-FE742895EBE2}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test", "Test\Test.csproj", "{7D0BA15A-EF3E-45D9-9ABB-603C79AF5CC3}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{CA725DFF-0A04-4BF5-B25D-1E1D16A67753}" 11 | ProjectSection(SolutionItems) = preProject 12 | .gitignore = .gitignore 13 | README.md = README.md 14 | EndProjectSection 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnsafeHelper.IL", "UnsafeHelper.IL\UnsafeHelper.IL.ilproj", "{C71D4520-B2E9-4321-8FD8-7C5A85EA06B6}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnsafeHelper.UnitTest", "UnsafeHelper.UnitTest\UnsafeHelper.UnitTest.csproj", "{EE51D7CD-08AF-4D81-AB99-638852AD8624}" 19 | EndProject 20 | <<<<<<< HEAD 21 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnsafeBenchmark", "UnsafeBenchmark\UnsafeBenchmark.csproj", "{1F64FBE4-1B1D-45EF-8A6B-39AD1EBF81D5}" 22 | ======= 23 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnsafeHelper.Test", "UnsafeHelper.Test\UnsafeHelper.Test.csproj", "{EC7719F1-594A-4A3B-9FE3-68501932ABDC}" 24 | >>>>>>> 4cc743076c0c11836e7a8a638aabc5a59ac06686 25 | EndProject 26 | Global 27 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 28 | Debug|Any CPU = Debug|Any CPU 29 | Debug|x64 = Debug|x64 30 | Debug|x86 = Debug|x86 31 | Release|Any CPU = Release|Any CPU 32 | Release|x64 = Release|x64 33 | Release|x86 = Release|x86 34 | EndGlobalSection 35 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 36 | {3E812CB3-589E-442E-8806-FE742895EBE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {3E812CB3-589E-442E-8806-FE742895EBE2}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {3E812CB3-589E-442E-8806-FE742895EBE2}.Debug|x64.ActiveCfg = Debug|Any CPU 39 | {3E812CB3-589E-442E-8806-FE742895EBE2}.Debug|x64.Build.0 = Debug|Any CPU 40 | {3E812CB3-589E-442E-8806-FE742895EBE2}.Debug|x86.ActiveCfg = Debug|x86 41 | {3E812CB3-589E-442E-8806-FE742895EBE2}.Debug|x86.Build.0 = Debug|x86 42 | {3E812CB3-589E-442E-8806-FE742895EBE2}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {3E812CB3-589E-442E-8806-FE742895EBE2}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {3E812CB3-589E-442E-8806-FE742895EBE2}.Release|x64.ActiveCfg = Release|Any CPU 45 | {3E812CB3-589E-442E-8806-FE742895EBE2}.Release|x64.Build.0 = Release|Any CPU 46 | {3E812CB3-589E-442E-8806-FE742895EBE2}.Release|x86.ActiveCfg = Release|Any CPU 47 | {3E812CB3-589E-442E-8806-FE742895EBE2}.Release|x86.Build.0 = Release|Any CPU 48 | {7D0BA15A-EF3E-45D9-9ABB-603C79AF5CC3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 49 | {7D0BA15A-EF3E-45D9-9ABB-603C79AF5CC3}.Debug|Any CPU.Build.0 = Debug|Any CPU 50 | {7D0BA15A-EF3E-45D9-9ABB-603C79AF5CC3}.Debug|x64.ActiveCfg = Debug|x64 51 | {7D0BA15A-EF3E-45D9-9ABB-603C79AF5CC3}.Debug|x64.Build.0 = Debug|x64 52 | {7D0BA15A-EF3E-45D9-9ABB-603C79AF5CC3}.Debug|x86.ActiveCfg = Debug|x86 53 | {7D0BA15A-EF3E-45D9-9ABB-603C79AF5CC3}.Debug|x86.Build.0 = Debug|x86 54 | {7D0BA15A-EF3E-45D9-9ABB-603C79AF5CC3}.Release|Any CPU.ActiveCfg = Release|Any CPU 55 | {7D0BA15A-EF3E-45D9-9ABB-603C79AF5CC3}.Release|Any CPU.Build.0 = Release|Any CPU 56 | {7D0BA15A-EF3E-45D9-9ABB-603C79AF5CC3}.Release|x64.ActiveCfg = Release|x64 57 | {7D0BA15A-EF3E-45D9-9ABB-603C79AF5CC3}.Release|x64.Build.0 = Release|x64 58 | {7D0BA15A-EF3E-45D9-9ABB-603C79AF5CC3}.Release|x86.ActiveCfg = Release|x86 59 | {7D0BA15A-EF3E-45D9-9ABB-603C79AF5CC3}.Release|x86.Build.0 = Release|x86 60 | {C71D4520-B2E9-4321-8FD8-7C5A85EA06B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 61 | {C71D4520-B2E9-4321-8FD8-7C5A85EA06B6}.Debug|Any CPU.Build.0 = Debug|Any CPU 62 | {C71D4520-B2E9-4321-8FD8-7C5A85EA06B6}.Debug|x64.ActiveCfg = Debug|Any CPU 63 | {C71D4520-B2E9-4321-8FD8-7C5A85EA06B6}.Debug|x64.Build.0 = Debug|Any CPU 64 | {C71D4520-B2E9-4321-8FD8-7C5A85EA06B6}.Debug|x86.ActiveCfg = Debug|Any CPU 65 | {C71D4520-B2E9-4321-8FD8-7C5A85EA06B6}.Debug|x86.Build.0 = Debug|Any CPU 66 | {C71D4520-B2E9-4321-8FD8-7C5A85EA06B6}.Release|Any CPU.ActiveCfg = Release|Any CPU 67 | {C71D4520-B2E9-4321-8FD8-7C5A85EA06B6}.Release|Any CPU.Build.0 = Release|Any CPU 68 | {C71D4520-B2E9-4321-8FD8-7C5A85EA06B6}.Release|x64.ActiveCfg = Release|Any CPU 69 | {C71D4520-B2E9-4321-8FD8-7C5A85EA06B6}.Release|x64.Build.0 = Release|Any CPU 70 | {C71D4520-B2E9-4321-8FD8-7C5A85EA06B6}.Release|x86.ActiveCfg = Release|Any CPU 71 | {C71D4520-B2E9-4321-8FD8-7C5A85EA06B6}.Release|x86.Build.0 = Release|Any CPU 72 | {EE51D7CD-08AF-4D81-AB99-638852AD8624}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 73 | {EE51D7CD-08AF-4D81-AB99-638852AD8624}.Debug|Any CPU.Build.0 = Debug|Any CPU 74 | {EE51D7CD-08AF-4D81-AB99-638852AD8624}.Debug|x64.ActiveCfg = Debug|Any CPU 75 | {EE51D7CD-08AF-4D81-AB99-638852AD8624}.Debug|x64.Build.0 = Debug|Any CPU 76 | {EE51D7CD-08AF-4D81-AB99-638852AD8624}.Debug|x86.ActiveCfg = Debug|Any CPU 77 | {EE51D7CD-08AF-4D81-AB99-638852AD8624}.Debug|x86.Build.0 = Debug|Any CPU 78 | {EE51D7CD-08AF-4D81-AB99-638852AD8624}.Release|Any CPU.ActiveCfg = Release|Any CPU 79 | {EE51D7CD-08AF-4D81-AB99-638852AD8624}.Release|Any CPU.Build.0 = Release|Any CPU 80 | {EE51D7CD-08AF-4D81-AB99-638852AD8624}.Release|x64.ActiveCfg = Release|Any CPU 81 | {EE51D7CD-08AF-4D81-AB99-638852AD8624}.Release|x64.Build.0 = Release|Any CPU 82 | {EE51D7CD-08AF-4D81-AB99-638852AD8624}.Release|x86.ActiveCfg = Release|Any CPU 83 | {EE51D7CD-08AF-4D81-AB99-638852AD8624}.Release|x86.Build.0 = Release|Any CPU 84 | <<<<<<< HEAD 85 | {1F64FBE4-1B1D-45EF-8A6B-39AD1EBF81D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 86 | {1F64FBE4-1B1D-45EF-8A6B-39AD1EBF81D5}.Debug|Any CPU.Build.0 = Debug|Any CPU 87 | {1F64FBE4-1B1D-45EF-8A6B-39AD1EBF81D5}.Debug|x64.ActiveCfg = Debug|Any CPU 88 | {1F64FBE4-1B1D-45EF-8A6B-39AD1EBF81D5}.Debug|x64.Build.0 = Debug|Any CPU 89 | {1F64FBE4-1B1D-45EF-8A6B-39AD1EBF81D5}.Debug|x86.ActiveCfg = Debug|Any CPU 90 | {1F64FBE4-1B1D-45EF-8A6B-39AD1EBF81D5}.Debug|x86.Build.0 = Debug|Any CPU 91 | {1F64FBE4-1B1D-45EF-8A6B-39AD1EBF81D5}.Release|Any CPU.ActiveCfg = Release|Any CPU 92 | {1F64FBE4-1B1D-45EF-8A6B-39AD1EBF81D5}.Release|Any CPU.Build.0 = Release|Any CPU 93 | {1F64FBE4-1B1D-45EF-8A6B-39AD1EBF81D5}.Release|x64.ActiveCfg = Release|Any CPU 94 | {1F64FBE4-1B1D-45EF-8A6B-39AD1EBF81D5}.Release|x64.Build.0 = Release|Any CPU 95 | {1F64FBE4-1B1D-45EF-8A6B-39AD1EBF81D5}.Release|x86.ActiveCfg = Release|Any CPU 96 | {1F64FBE4-1B1D-45EF-8A6B-39AD1EBF81D5}.Release|x86.Build.0 = Release|Any CPU 97 | ======= 98 | {EC7719F1-594A-4A3B-9FE3-68501932ABDC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 99 | {EC7719F1-594A-4A3B-9FE3-68501932ABDC}.Debug|Any CPU.Build.0 = Debug|Any CPU 100 | {EC7719F1-594A-4A3B-9FE3-68501932ABDC}.Debug|x64.ActiveCfg = Debug|Any CPU 101 | {EC7719F1-594A-4A3B-9FE3-68501932ABDC}.Debug|x64.Build.0 = Debug|Any CPU 102 | {EC7719F1-594A-4A3B-9FE3-68501932ABDC}.Debug|x86.ActiveCfg = Debug|Any CPU 103 | {EC7719F1-594A-4A3B-9FE3-68501932ABDC}.Debug|x86.Build.0 = Debug|Any CPU 104 | {EC7719F1-594A-4A3B-9FE3-68501932ABDC}.Release|Any CPU.ActiveCfg = Release|Any CPU 105 | {EC7719F1-594A-4A3B-9FE3-68501932ABDC}.Release|Any CPU.Build.0 = Release|Any CPU 106 | {EC7719F1-594A-4A3B-9FE3-68501932ABDC}.Release|x64.ActiveCfg = Release|Any CPU 107 | {EC7719F1-594A-4A3B-9FE3-68501932ABDC}.Release|x64.Build.0 = Release|Any CPU 108 | {EC7719F1-594A-4A3B-9FE3-68501932ABDC}.Release|x86.ActiveCfg = Release|Any CPU 109 | {EC7719F1-594A-4A3B-9FE3-68501932ABDC}.Release|x86.Build.0 = Release|Any CPU 110 | >>>>>>> 4cc743076c0c11836e7a8a638aabc5a59ac06686 111 | EndGlobalSection 112 | GlobalSection(SolutionProperties) = preSolution 113 | HideSolutionNode = FALSE 114 | EndGlobalSection 115 | GlobalSection(ExtensibilityGlobals) = postSolution 116 | SolutionGuid = {A6C93FC5-8591-495F-BEB4-ADA761C82CED} 117 | EndGlobalSection 118 | EndGlobal 119 | -------------------------------------------------------------------------------- /UnsafeHelper/ManagedObject.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace IlyfairyLib.Unsafe; 5 | 6 | /// 7 | /// 自动回收的托管对象 8 | /// 9 | /// 10 | [Obsolete("可能会导致对象丢失")] 11 | public unsafe class ManagedObject where T : class 12 | { 13 | /// 14 | /// 前(nint)字节为TypeHandle 15 | /// 16 | private readonly byte[] data; 17 | public int Size => data.Length; 18 | public nint* Handle => (nint*)(UnsafeHelper.GetRawDataPointer(data) + 8); 19 | public T Object { get; private set; } 20 | private readonly GCHandle gcHandle; 21 | private ManagedObject(byte[] data, object obj) 22 | { 23 | Object = System.Runtime.CompilerServices.Unsafe.As(obj); 24 | this.data = data; 25 | } 26 | public ManagedObject(int size) 27 | { 28 | if (size <= 8) size = 8; 29 | size += 8; 30 | data = new byte[size]; 31 | var handle = Handle; 32 | *handle = typeof(T).TypeHandle.Value; 33 | Object = System.Runtime.CompilerServices.Unsafe.Read(&handle); 34 | gcHandle = GCHandle.Alloc(Object); 35 | } 36 | ~ManagedObject() 37 | { 38 | gcHandle.Free(); 39 | } 40 | public Span GetDataSpan() where T : unmanaged => new((byte*)Handle + sizeof(nint), Size / sizeof(T)); 41 | public void ChangeType(Type type) => *Handle = type.TypeHandle.Value; 42 | public void ChangeType() => *Handle = typeof(T).TypeHandle.Value; 43 | public ManagedObject As() where TTo : class => System.Runtime.CompilerServices.Unsafe.As>(this); 44 | } 45 | -------------------------------------------------------------------------------- /UnsafeHelper/MethodTable.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace IlyfairyLib.Unsafe 5 | { 6 | // /// 7 | // /// 方法表 8 | // /// 9 | // [StructLayout(LayoutKind.Explicit)] 10 | // public unsafe struct MethodTable 11 | // { 12 | // public const int PtrSize = 13 | //#if TARGET_64BIT 14 | // 8 15 | //#else 16 | // 4 17 | //#endif 18 | // ; 19 | 20 | // /// 21 | // /// 的每个元素大小 22 | // /// 23 | // [FieldOffset(0)] 24 | // public ushort ComponentSize; // m_dwFlags lower 16bits 25 | 26 | // /// 27 | // /// 低16位表示 的每个元素大小 28 | // /// 29 | // [FieldOffset(0)] 30 | // public uint Flags; // m_dwFlags 31 | 32 | // /// 33 | // /// 申请本类型实例时将使用多少字节 34 | // /// 35 | // [FieldOffset(4)] 36 | // public uint BaseSize; // m_BaseSize 37 | 38 | // // 0x8: m_wFlags2 39 | 40 | // // 0xA: m_wToken 41 | 42 | // /// 43 | // /// 虚方法计数 44 | // /// 45 | // [FieldOffset(0xC)] 46 | // public ushort VirtualsCount; // m_wNumVirtuals 47 | 48 | // /// 49 | // /// 实现接口计数 50 | // /// 51 | // [FieldOffset(0xE)] 52 | // public ushort InterfaceCount; // m_wNumInterfaces 53 | 54 | // /// 55 | // /// 父类方法表指针 56 | // /// 57 | // [FieldOffset(0x10)] 58 | // public MethodTable* ParentMethodTable; // m_pParentMethodTable 59 | 60 | // /// 61 | // /// per-instantiation information 62 | // /// 63 | // [FieldOffset(0x10 + 4 * PtrSize)] 64 | // public void* PerInstInfo; // m_pPerInstInfo 65 | 66 | // /// 67 | // /// 数组成员类型的 68 | // /// 69 | // [FieldOffset(0x10 + 4 * PtrSize)] 70 | // public void* ElementType; // m_ElementTypeHnd 71 | 72 | // /// 73 | // /// 实现接口方法表 74 | // /// 75 | // [FieldOffset(0x10 + 5 * PtrSize)] 76 | // public MethodTable** InterfaceMap; // m_pInterfaceMap 77 | // } 78 | 79 | /// 80 | /// Subset of src\vm\methodtable.h 81 | /// 82 | //[StructLayout(LayoutKind.Sequential)] 83 | public unsafe struct MethodTable 84 | { 85 | internal ComponentSize_Flags_0 ComponentSize_Flags; 86 | /// 87 | /// 的元素大小 88 | /// 89 | public ref ushort ComponentSize => ref ComponentSize_Flags.ComponentSize; // offset:0 90 | /// 91 | /// EETypeFlags
92 | /// 当前的Flag (仅适用于非) 93 | ///
94 | public ref uint Flags => ref ComponentSize_Flags.Flags; // offset:0 95 | 96 | /// 97 | /// 类型的基本大小 (在堆上分配实例时使用) 98 | /// 99 | //[FieldOffset(4)] 100 | public uint BaseSize; // offset:4 101 | 102 | // 0x8: m_wFlags2 103 | private ushort m_wFlags2; // offset:8 104 | 105 | // 0xA: m_wToken 106 | private ushort m_wToken; // offset:10 107 | 108 | /// 109 | /// 虚方法个数 110 | /// 111 | //[FieldOffset(0xC)] 112 | public ushort VirtualsCount; // offset:12 113 | 114 | /// 115 | /// 接口个数 116 | /// 117 | //[FieldOffset(0xE)] 118 | public ushort InterfaceCount; // offset:14 119 | 120 | //private nint debug_m_szClassName; // offset:16 121 | 122 | /// 123 | /// 父类的 124 | /// 125 | //[FieldOffset(0x10)] 126 | public MethodTable* ParentMethodTable; //offset:16 127 | 128 | private nint unknown1, unknown2, unknown3; 129 | 130 | /// 131 | /// 数组成员类型的 132 | /// 133 | //[FieldOffset(0x10 + 4 * PtrSize)] 134 | public void* ElementType; //offset: x86:32 x64:48 135 | 136 | /// 137 | /// 实现接口的 138 | /// 139 | //[FieldOffset(0x10 + 5 * PtrSize)] 140 | public MethodTable** InterfaceMap; //offset: x86:36 x64:56 141 | 142 | [StructLayout(LayoutKind.Explicit, Size = 4)] 143 | internal struct ComponentSize_Flags_0 144 | { 145 | [FieldOffset(0)] 146 | public ushort ComponentSize; 147 | 148 | [FieldOffset(0)] 149 | public uint Flags; 150 | } 151 | 152 | 153 | public bool IsValueType 154 | { 155 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 156 | get => (Flags & 0xc0000U) == 0x40000U; 157 | } 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /UnsafeHelper/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "UnsafeHelper": { 4 | "commandName": "Project", 5 | "environmentVariables": { 6 | "DOTNET_JitDisasm": "IlyfairyLib.Unsafe.UnsafeHelper:*", 7 | "DOTNET_TieredCompilation": "0" 8 | } 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /UnsafeHelper/StructExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace IlyfairyLib.Unsafe; 8 | 9 | public static class StructExtension 10 | { 11 | public static unsafe TStruct ToStruct(this byte[] bytes) where TStruct : struct 12 | { 13 | if (sizeof(TStruct) != bytes.Length) 14 | throw new ArgumentOutOfRangeException(nameof(bytes), "Bytes array should be the same length as struct size."); 15 | TStruct val; 16 | fixed (byte* p = bytes) 17 | { 18 | Buffer.MemoryCopy(p, &val, (ulong)sizeof(TStruct), (ulong)sizeof(TStruct)); 19 | return val; 20 | } 21 | } 22 | 23 | public static unsafe TStruct ToStruct(this Span bytes) where TStruct : struct 24 | { 25 | if (sizeof(TStruct) != bytes.Length) 26 | throw new ArgumentOutOfRangeException(nameof(bytes), "Bytes array should be the same length as struct size."); 27 | TStruct val; 28 | fixed (byte* p = bytes) 29 | { 30 | Buffer.MemoryCopy(p, &val, (ulong)sizeof(TStruct), (ulong)sizeof(TStruct)); 31 | return val; 32 | } 33 | } 34 | 35 | public static unsafe void ToStruct(this byte[] bytes, ref TStruct reference) where TStruct : struct 36 | { 37 | if (sizeof(TStruct) != bytes.Length) 38 | throw new ArgumentOutOfRangeException(nameof(bytes), "Bytes array should be the same length as struct size."); 39 | fixed (byte* p = bytes) 40 | { 41 | Buffer.MemoryCopy(p, System.Runtime.CompilerServices.Unsafe.AsPointer(ref reference), (ulong)sizeof(TStruct), (ulong)sizeof(TStruct)); 42 | } 43 | } 44 | 45 | public static unsafe void ToStruct(this Span bytes, ref TStruct reference) where TStruct : struct 46 | { 47 | if (sizeof(TStruct) != bytes.Length) 48 | throw new ArgumentOutOfRangeException(nameof(bytes), "Bytes array should be the same length as struct size."); 49 | fixed (byte* p = bytes) 50 | { 51 | Buffer.MemoryCopy(p, System.Runtime.CompilerServices.Unsafe.AsPointer(ref reference), (ulong)sizeof(TStruct), (ulong)sizeof(TStruct)); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /UnsafeHelper/UnsafeHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.CodeAnalysis; 3 | using System.Reflection; 4 | using System.Runtime.CompilerServices; 5 | using System.Runtime.InteropServices; 6 | using System.Text; 7 | //using IlyfairyLib.Unsafe.Internal; 8 | using UnsafeCore = System.Runtime.CompilerServices.Unsafe; 9 | 10 | #pragma warning disable CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type 11 | namespace IlyfairyLib.Unsafe 12 | { 13 | internal sealed class RawData 14 | { 15 | public byte Data; 16 | } 17 | 18 | [StructLayout(LayoutKind.Explicit)] 19 | internal struct ObjectHeader 20 | { 21 | #if TARGET_64BIT 22 | [FieldOffset(4)] 23 | #else 24 | [FieldOffset(0)] 25 | #endif 26 | public uint SyncBlockValue; 27 | } 28 | 29 | /// 30 | /// Unsafe的工具方法 31 | /// 32 | public static unsafe class UnsafeHelper 33 | { 34 | private static readonly Type RuntimeHelpersType; 35 | private static readonly Func? AllocateUninitializedClone; 36 | private static readonly int m_fieldHandle_offset = -1; // RtFieldInfo中的m_fieldHandle的偏移地址 37 | 38 | private static readonly delegate* unmanaged AllocateUninitializedClone2; 39 | 40 | //static UnsafeHelper() 41 | //{ 42 | // RuntimeHelpersType = typeof(RuntimeHelpers); 43 | // AllocateUninitializedClone = (Func?)RuntimeHelpersType.GetMethod("AllocateUninitializedClone", BindingFlags.Static | BindingFlags.NonPublic)?.CreateDelegate(typeof(Func)); 44 | 45 | // //获取RtFieldInfo中的m_fieldHandle 46 | // //var info = typeof(UnsafeHelper).GetField("m_fieldHandle_offset", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); //只是为了获取一个RtFieldInfo实例 47 | // //var m_fieldHandleInfo = info.GetType().GetField("m_fieldHandle", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); 48 | // var m_fieldHandleInfo = typeof(FieldInfo).Assembly.GetType("System.Reflection.RtFieldInfo")?.GetField("m_fieldHandle", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); 49 | // if (m_fieldHandleInfo == null) return; 50 | // var addr = (IntPtr*)GetObjectRawDataAddress(m_fieldHandleInfo); 51 | // var m_fieldHandle = (IntPtr)m_fieldHandleInfo.GetValue(m_fieldHandleInfo)!; 52 | 53 | // //获取m_fieldHandle的偏移地址 54 | // int size = (int)GetObjectRawDataSize(m_fieldHandleInfo); 55 | // for (int i = 0; i < size; i += 1) 56 | // { 57 | // if (m_fieldHandle == addr[i]) 58 | // { 59 | // m_fieldHandle_offset = i * sizeof(IntPtr); 60 | // break; 61 | // } 62 | // } 63 | //} 64 | 65 | static UnsafeHelper() 66 | { 67 | RuntimeHelpersType = typeof(RuntimeHelpers); 68 | AllocateUninitializedClone = (Func?)RuntimeHelpersType.GetMethod("AllocateUninitializedClone", BindingFlags.Static | BindingFlags.NonPublic)?.CreateDelegate(typeof(Func)); 69 | //获取RtFieldInfo中的m_fieldHandle 70 | //var info = typeof(UnsafeHelper).GetField("m_fieldHandle_offset", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); //只是为了获取一个RtFieldInfo实例 71 | //var m_fieldHandleInfo = info.GetType().GetField("m_fieldHandle", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); 72 | var m_fieldHandleInfo = typeof(FieldInfo).Assembly.GetType("System.Reflection.RtFieldInfo")?.GetField("m_fieldHandle", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); 73 | if (m_fieldHandleInfo == null) return; 74 | var addr = (nint*)GetRawDataPointer(m_fieldHandleInfo); 75 | var m_fieldHandle = (nint)m_fieldHandleInfo.GetValue(m_fieldHandleInfo)!; 76 | 77 | //获取m_fieldHandle的偏移地址 78 | int size = (int)GetRawDataSize(m_fieldHandleInfo); 79 | for (int i = 0; i < size; i += 1) 80 | { 81 | if (m_fieldHandle == addr[i]) 82 | { 83 | m_fieldHandle_offset = i * sizeof(nint); 84 | break; 85 | } 86 | } 87 | } 88 | 89 | #region GetPointer 90 | /// 91 | /// 获取引用的地址 92 | /// 93 | /// 94 | /// 95 | /// address 96 | [Obsolete] 97 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 98 | public static byte* GetPointer(ref T val) => (byte*)UnsafeCore.AsPointer(ref val); 99 | //{ 100 | // fixed(void* p = &val) 101 | // { 102 | // return (IntPtr)p; 103 | // } 104 | //} 105 | 106 | /// 107 | /// 获取对象实例的地址(**) 108 | /// 109 | /// 110 | /// address 111 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 112 | public static MethodTable** GetPointer(object obj) 113 | { 114 | //return (MethodTable**)UnsafeCore.AsPointer(ref UnsafeCore.Add(ref GetRawDataReference(obj), -sizeof(nint))); 115 | return *(MethodTable***)&obj; 116 | } 117 | #endregion 118 | 119 | #region GetRawData 120 | /// 121 | /// 获取对象数据区域的地址 122 | /// 123 | /// 124 | /// 125 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 126 | public static ref byte GetRawDataReference(object obj) => ref UnsafeCore.As(obj).Data; 127 | 128 | /// 129 | /// 获取对象数据区域的地址 130 | /// 131 | /// 132 | /// 133 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 134 | public static byte* GetRawDataPointer(object obj) => (byte*)UnsafeCore.AsPointer(ref GetRawDataReference(obj)); 135 | #endregion 136 | 137 | #region GetMethodTable 138 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 139 | public static ref MethodTable GetMethodTableReference(object obj) => ref UnsafeCore.AsRef(GetMethodTablePointer(obj)); 140 | 141 | [MethodImpl(MethodImplOptions.AggressiveOptimization)] 142 | public static MethodTable* GetMethodTablePointer(object obj) => (MethodTable*)UnsafeCore.Add(ref UnsafeCore.As(ref GetRawDataReference(obj)), -1); 143 | #endregion 144 | 145 | #region GetObjectHeader 146 | [MethodImpl(MethodImplOptions.AggressiveOptimization)] 147 | public static uint* GetObjectHeaderPointer(object obj) 148 | { 149 | return (uint*)UnsafeCore.AsPointer(ref UnsafeCore.As(ref UnsafeCore.Subtract(ref GetRawDataReference(obj), sizeof(nint) + 4))); 150 | } 151 | 152 | [MethodImpl(MethodImplOptions.AggressiveOptimization)] 153 | public static ref uint GetObjectHeaderReference(object obj) 154 | { 155 | return ref UnsafeCore.As(ref UnsafeCore.Subtract(ref GetRawDataReference(obj), sizeof(nint) + 4)); 156 | } 157 | #endregion 158 | 159 | /// 160 | /// 获取对象数据的Span 161 | /// 162 | /// 163 | /// 164 | public static Span GetObjectRawDataAsSpan(object obj) where T : unmanaged 165 | { 166 | byte* first = GetRawDataPointer(obj); 167 | nuint size = (nuint)GetRawDataSize(obj) / (uint)sizeof(T); 168 | return new Span(first, checked((int)size)); 169 | } 170 | 171 | /// 172 | /// 获取对象的数据区域在堆中的大小 173 | /// 174 | /// 175 | /// 176 | public static nuint GetRawDataSize(object obj) 177 | { 178 | [DoesNotReturn] 179 | static void Throw() => throw new ArgumentNullException(nameof(obj)); 180 | if (obj == null) Throw(); 181 | ref MethodTable mt = ref GetMethodTableReference(obj); 182 | nuint rawSize = mt.BaseSize - (uint)(2 * sizeof(nuint)); 183 | //if ((mt.Flags >> 31) != 0) // HasComponentSizeFlag = 0x80000000 184 | //if (BitConverter.IsLittleEndian ? (mt.Flags >> 31) != 0 : (uint)(byte)mt.Flags >> 31 != 0) 185 | if ((int)mt.Flags < 0) 186 | { 187 | rawSize += UnsafeCore.As(ref GetRawDataReference(obj)) * (nuint)mt.ComponentSize; 188 | } 189 | return rawSize; 190 | } 191 | 192 | /// 193 | /// 获取对象的数据区域在堆中的大小, 不计算的成员大小 194 | /// 195 | /// 196 | public static nuint GetRawDataSize() 197 | { 198 | ref MethodTable mt = ref UnsafeCore.AsRef((void*)typeof(T).TypeHandle.Value); 199 | bool empty = mt.BaseSize != 0; 200 | //if (empty) return 0; 201 | //return mt.BaseSize - (sizeof(nint) * 2); 202 | 203 | // empty != 0 -> 1 , -1 = 0xffffffff & val = val 204 | // empty == 0 -> 0 , 0 & any = 0 205 | return (nuint)(mt.BaseSize - (2 * (uint)sizeof(nuint)) & -UnsafeCore.As(ref empty)); // 对于 Array 类型, 由于长度在实例中, 不计算数组成员所占大小 206 | } 207 | 208 | //[MethodImpl(MethodImplOptions.AggressiveOptimization)] 209 | //public static nuint GetRawObjectDataSize(object obj) // System.Runtime.CompilerServices.RuntimeHelpers.GetRawObjectDataSize 210 | //{ 211 | // ref MethodTable mt = ref GetMethodTableReference(obj); 212 | // nuint rawSize = mt.BaseSize - (uint)(2 * sizeof(nuint)); 213 | // //if ((mt.Flags >> 31) != 0) // HasComponentSizeFlag = 0x80000000 214 | // //if (BitConverter.IsLittleEndian ? (mt.Flags >> 31) != 0 : (uint)(byte)mt.Flags >> 31 != 0) 215 | // if((int)mt.Flags < 0) 216 | // { 217 | // rawSize += UnsafeCore.As(ref GetRawDataReference(obj)) * (nuint)mt.ComponentSize; 218 | // } 219 | // return rawSize; 220 | //} 221 | 222 | /// 223 | /// 获取结构体大小 224 | /// 225 | /// 226 | /// 227 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 228 | public static int GetStructSize() where T : struct => sizeof(T); 229 | 230 | /// 231 | /// 克隆一个对象 232 | /// 233 | /// 234 | /// 235 | /// 236 | public static T? Clone(this T obj) where T : class 237 | { 238 | [DoesNotReturn] 239 | static void Throw() => throw new ArgumentNullException(nameof(obj)); 240 | if (obj == null) Throw(); 241 | T? newObj = CloneEmptyObject(obj); //克隆对象 242 | if (newObj == null) return null; 243 | nuint size = (nuint)GetRawDataSize(obj); //长度 244 | byte* oldPtr = GetRawDataPointer(obj); //旧的地址 245 | byte* newPtr = GetRawDataPointer(newObj); //新的地址 246 | Buffer.MemoryCopy(oldPtr, newPtr, size, size); 247 | GC.KeepAlive(obj); 248 | return newObj; 249 | } 250 | 251 | /// 252 | /// 克隆至空的对象 253 | /// 254 | /// 255 | /// 256 | /// 257 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 258 | public static T? CloneEmptyObject(T obj) where T : class 259 | { 260 | if (obj == null) throw new ArgumentNullException(nameof(obj)); 261 | if (AllocateUninitializedClone == null) return null; 262 | return (T)AllocateUninitializedClone(obj); 263 | } 264 | 265 | #region ToStringAddress 266 | /// 267 | /// 返回地址字符串 268 | /// 269 | /// 270 | /// 271 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 272 | public static string ToAddress(this nuint ptr) 273 | { 274 | //int size = 2 + sizeof(nint); 275 | //var str = new string('\0', 0); 276 | //fixed (char* p = str) 277 | //{ 278 | // p[0] = '0'; 279 | // p[1] = 'x'; 280 | // for (int i = 2; i < size; i++) 281 | // { 282 | 283 | // } 284 | //} 285 | return "0x" + ((ulong)ptr).ToString("X").PadLeft(sizeof(UIntPtr) * 2, '0'); 286 | } 287 | 288 | /// 289 | /// 返回地址字符串 290 | /// 291 | /// 292 | /// 293 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 294 | public static string ToAddress(this nint ptr) 295 | { 296 | return "0x" + ptr.ToString("X").PadLeft(sizeof(IntPtr) * 2, '0'); 297 | } 298 | #endregion 299 | 300 | /// 301 | /// 修改对象类型(Handle) 302 | /// 303 | /// 304 | /// 305 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 306 | public static object ChangeObjectHandle(object obj, Type type) // 等会儿需要反汇编 307 | { 308 | //*(MethodTable**)UnsafeCore.AsPointer(ref obj) = (MethodTable*)type.TypeHandle.Value; //会报错 309 | //var mt = (MethodTable*)*(nint**)&obj; //x 310 | //* *(nint**)&obj = type.TypeHandle.Value; 311 | //*GetMethodTablePointer(obj) = (MethodTable*)type.TypeHandle.Value; //也会报错 312 | //*GetPointer(obj) = (MethodTable*)type.TypeHandle.Value; 313 | *(void**)GetPointer(obj) = (void*)type.TypeHandle.Value; 314 | return obj; 315 | } 316 | 317 | /// 318 | /// 修改对象类型(Handle) 319 | /// 320 | /// 321 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 322 | public static T ChangeObjectHandle(object obj) where T : class 323 | { 324 | *(IntPtr*)GetPointer(obj) = typeof(T).TypeHandle.Value; 325 | return UnsafeCore.As(obj); 326 | } 327 | 328 | /// 329 | /// 申请一个对象,通过FreeObject释放 330 | /// 331 | /// 332 | /// 333 | /// 334 | public static object AllocObject(Type type, nuint rawDataSize) 335 | { 336 | if (rawDataSize < 0) throw new ArgumentOutOfRangeException(nameof(rawDataSize)); 337 | rawDataSize += 16; 338 | #if NET6_0_OR_GREATER 339 | var p = (nint*)NativeMemory.AllocZeroed(rawDataSize); 340 | if (p == null) throw new OutOfMemoryException(); 341 | #else 342 | var p = (nint*)Marshal.AllocHGlobal((nint)rawDataSize); 343 | if (p == null) throw new OutOfMemoryException(); 344 | Zero((void*)p, checked((nuint)rawDataSize + (nuint)sizeof(IntPtr))); 345 | #endif 346 | p[1] = type.TypeHandle.Value; 347 | var obj = &p[1]; 348 | //var obj = CoreUnsafe.Read(&p); 349 | return *(object*)&obj; 350 | } 351 | 352 | // TODO: nuint 353 | //public static object AllocObject(Type type, nint size) 354 | //{ 355 | 356 | //} 357 | 358 | /// 359 | /// 申请一个对象,通过FreeObject释放 360 | /// 361 | /// 362 | /// 363 | public static T AllocObject(nuint size) where T : class 364 | { 365 | object obj = AllocObject(typeof(T), size); 366 | return UnsafeCore.As(ref obj); 367 | } 368 | 369 | /// 370 | /// 申请一个对象,通过FreeObject释放 371 | /// 372 | /// 373 | public static T AllocObject() where T : class 374 | { 375 | var rawSize = GetRawDataSize(); 376 | if (rawSize < 0) rawSize = 0; 377 | var size = (uint)(rawSize + (nuint)IntPtr.Size); 378 | return UnsafeCore.As(AllocObject(typeof(T), (nuint)size)); 379 | } 380 | 381 | /// 382 | /// 内存清0 383 | /// 384 | /// 385 | /// 386 | /// 387 | public static void Zero(void* p, nuint size) 388 | { 389 | while (size > uint.MaxValue) 390 | { 391 | MemoryMarshal.CreateSpan(ref *(byte*)p, -1).Clear(); 392 | size -= uint.MaxValue; 393 | p = (byte*)p + uint.MaxValue; 394 | } 395 | MemoryMarshal.CreateSpan(ref *(byte*)p, (int)size).Clear(); 396 | } 397 | 398 | /// 399 | /// 释放AllocObject创建的对象 400 | /// 401 | /// 402 | public static void FreeObject(object obj) 403 | { 404 | var p = (void**)GetObjectHeaderPointer(obj); 405 | #if NET6_0_OR_GREATER 406 | NativeMemory.Free(p); 407 | #else 408 | Marshal.FreeHGlobal((nint)p); 409 | #endif 410 | } 411 | 412 | /// 413 | /// 通过AllocateUninitializedClone克隆出一个新的对象,不经过构造函数,由GC自动回收 414 | /// 415 | /// 416 | /// 417 | public static unsafe object NewObject(Type type) 418 | { 419 | var data = ( 420 | SyncBlock: IntPtr.Zero, 421 | MethodTablePtr: type.TypeHandle.Value, 422 | RawData: IntPtr.Zero); 423 | var p = &data.MethodTablePtr; 424 | var obj = *(object*)&p ?? throw new NotSupportedException(); 425 | var clone = AllocateUninitializedClone(obj); 426 | return clone; 427 | } 428 | /// 429 | /// 通过AllocateUninitializedClone克隆出一个新的对象,不经过构造函数,由GC自动回收 430 | /// 431 | /// 432 | /// 433 | public static unsafe T NewObject() where T : class 434 | { 435 | return UnsafeCore.As(NewObject(typeof(T))); 436 | } 437 | 438 | /// 439 | /// 将字符串转换成 Span<char> 440 | /// 441 | /// 字符串 442 | /// 443 | public static Span AsSpan(string str) 444 | { 445 | var span = str.AsSpan(); 446 | return MemoryMarshal.CreateSpan(ref MemoryMarshal.GetReference(span), span.Length); 447 | } 448 | 449 | ///// 450 | ///// 比较两个对象的原始数据是否相等
不比较类型 451 | /////
452 | ///// 453 | ///// 454 | ///// 455 | //public static bool CompareRaw(object obj1, object obj2) 456 | //{ 457 | // long obj1size = UnsafeHelper.GetRawDataSize(obj1); 458 | // long obj2size = UnsafeHelper.GetRawDataSize(obj2); 459 | // if (obj1size != obj2size) return false; 460 | 461 | // ulong lenByte = (uint)obj1size; 462 | // byte* r1 = GetRawDataPointer(obj1); 463 | // byte* r2 = GetRawDataPointer(obj2); 464 | 465 | // return true; 466 | // // Call SpanHelpers.SequenceEqual 467 | //} 468 | 469 | /// 470 | /// 将[多维]数组转换为Span 471 | /// 472 | /// 数组元素类型 473 | /// 多维数组 474 | /// 475 | public static Span AsSpan(this Array array/*, int rank*/) 476 | { 477 | if (array == null) throw new ArgumentNullException(nameof(array)); 478 | int len = array.Length; 479 | #if NET6_0_OR_GREATER 480 | var p = UnsafeCore.AsPointer(ref MemoryMarshal.GetArrayDataReference(array)); 481 | #else 482 | int rank = array.Rank; 483 | if (rank <= 1) rank = 0; 484 | byte* addr = GetRawDataPointer(array); 485 | int offset = rank * 8; 486 | // arrDataPtr + (Length/Padding) + rank 487 | var p = (byte*)addr + sizeof(nint) + offset; 488 | #endif 489 | return new Span(p, checked((int)(len * (long)GetArrayItemSize(array) / sizeof(T)))); 490 | } 491 | 492 | /// 493 | /// 父类数据复制到子类 494 | /// 495 | /// 父类/基类 496 | /// 子类/派生类 497 | /// 498 | public static void CopyParentToChild(TParent parentObj, TChild childObj) 499 | where TParent : class 500 | where TChild : class, TParent 501 | { 502 | if (parentObj == null) throw new ArgumentNullException(nameof(parentObj)); 503 | if (childObj == null) throw new ArgumentNullException(nameof(childObj)); 504 | 505 | byte* old = GetRawDataPointer(parentObj); 506 | byte* data = GetRawDataPointer(childObj); 507 | 508 | var len = GetRawDataSize(parentObj); 509 | 510 | Copy((void*)old, (void*)data, len); 511 | } 512 | 513 | /// 514 | /// 子类数据复制到父类 515 | /// 516 | /// 父类/基类 517 | /// 子类/派生类 518 | /// 519 | public static void CopyChildToParent(TChild childObj, TParent parentObj) 520 | where TParent : class 521 | where TChild : class, TParent 522 | { 523 | if (parentObj == null) throw new ArgumentNullException(nameof(parentObj)); 524 | if (childObj == null) throw new ArgumentNullException(nameof(childObj)); 525 | 526 | byte* old = GetRawDataPointer(childObj); 527 | byte* data = GetRawDataPointer(parentObj); 528 | 529 | var len = GetRawDataSize(parentObj); 530 | 531 | Copy((void*)old, (void*)data, len); 532 | } 533 | 534 | /// 535 | /// 获取数组中每个元素占用的大小, 数组元素的大小不会超过65535字节 536 | /// 537 | /// 538 | /// 539 | public static int GetArrayItemSize(Array array) 540 | { 541 | return GetMethodTablePointer(array)->ComponentSize; 542 | //return *(ushort*)array.GetType().TypeHandle.Value; 543 | } 544 | 545 | ///// 546 | ///// 获取数组第0的值的指针 547 | ///// 548 | ///// 549 | ///// 550 | ///// 551 | //[MethodImpl(MethodImplOptions.AggressiveInlining)] 552 | //public static T* ToPointer(this T[] str) // where T : unmanaged 553 | //{ 554 | // return (T*)((byte*)GetPointer(str) + (sizeof(IntPtr) * 2)); 555 | //} 556 | 557 | /// 558 | /// 设置值 559 | /// 560 | /// 561 | /// 562 | /// 563 | public static void SetValue(nint ptr, TValue value) => *(TValue*)ptr = value; 564 | public static void SetValue(void* ptr, TValue value) => *(TValue*)ptr = value; 565 | public static void SetValue(ref TFrom ptr, TValue value) => UnsafeCore.As(ref ptr) = value; 566 | 567 | /// 568 | /// 设置值
569 | /// 如果是class,自动设置它的RawData的值
570 | /// 如果是struct,自动设置它的值 571 | ///
572 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 573 | public static void SetValueAuto(nint ptr, TValue value) => SetValueAuto((void*)ptr, value); 574 | 575 | /// 576 | /// 设置值
577 | /// 如果是class,自动设置它的RawData的值
578 | /// 如果是struct,自动设置它的值 579 | ///
580 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 581 | public static void SetValueAuto(ref TFrom ptr, TValue value) => SetValueAuto(GetPointer(ref ptr), value); 582 | 583 | /// 584 | /// 设置值
585 | /// 如果是class,自动设置它的RawData的值
586 | /// 如果是struct,自动设置它的值 587 | ///
588 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 589 | public static void SetValueAuto(void* ptr, TValue value) 590 | { 591 | if(value is ValueType) 592 | { 593 | *(TValue*)ptr = value; 594 | } 595 | else 596 | { 597 | var data = GetRawDataPointer(value); 598 | var size = GetRawDataSize(value); 599 | Copy(data, (void*)ptr, size); 600 | } 601 | } 602 | 603 | #if NET7_0_OR_GREATER 604 | public static void Copy(void* source,void* destination, nint size) => NativeMemory.Copy(source, destination, checked((nuint)size)); 605 | public static void Copy(void* source,void* destination, nuint size) => NativeMemory.Copy(source, destination, size); 606 | #else 607 | public static void Copy(void* source,void* destination, nint size) => Buffer.MemoryCopy(source, destination, size, size); 608 | public static void Copy(void* source,void* destination, nuint size) => Buffer.MemoryCopy(source, destination, size, size); 609 | #endif 610 | 611 | /// 612 | /// 获取已装箱的值类型的引用 613 | /// 614 | /// 615 | /// 已装箱的值类型 616 | /// 617 | public static ref T GetBoxedReference(object boxedObject) where T : struct 618 | { 619 | return ref UnsafeCore.As(ref GetRawDataReference(boxedObject)); 620 | } 621 | /// 622 | /// 获取已装箱的值类型的指针 623 | /// 624 | /// 625 | /// 已装箱的值类型 626 | /// 627 | public static T* GetBoxedPointer(object boxedObject) where T : struct 628 | { 629 | return (T*)GetRawDataPointer(boxedObject); 630 | } 631 | 632 | 633 | #region Field 634 | /// 635 | /// 获取实例字段 636 | /// 637 | /// 638 | /// 639 | public static FieldInfo[] GetInstanceFields(Type type) => type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); 640 | 641 | /// 642 | /// 获取字段偏移 643 | /// 最大只能获取到65535的偏移 644 | /// 645 | /// 646 | /// 647 | /// 648 | /// 无法获取m_fieldHandle偏移地址 649 | public static int GetFieldOffset(Type type, string fieldName) 650 | { 651 | [DoesNotReturn] 652 | static void Throw() => throw new Exception($"not found field: {nameof(fieldName)}"); 653 | if (m_fieldHandle_offset < 0) throw new NotSupportedException(); 654 | var fieldInfo = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); 655 | if (fieldInfo == null) Throw(); 656 | return GetFieldOffset(fieldInfo); 657 | } 658 | 659 | /// 660 | /// 获取字段偏移 661 | /// 最大只能获取到65535的偏移 662 | /// 663 | /// 664 | /// 无法获取m_fieldHandle偏移地址 665 | public static int GetFieldOffset(FieldInfo fieldInfo) 666 | { 667 | [DoesNotReturn] 668 | static void Throw() => throw new ArgumentNullException(nameof(fieldInfo)); 669 | if (fieldInfo is null) Throw(); 670 | byte* fieldInfoAddr = GetRawDataPointer(fieldInfo); 671 | IntPtr fieldHandle = *(IntPtr*)(fieldInfoAddr + m_fieldHandle_offset); 672 | return *(ushort*)(fieldHandle + sizeof(IntPtr) + 4); 673 | } 674 | 675 | /// 676 | /// 获取字段地址 677 | /// 678 | /// 679 | /// 680 | /// 681 | /// 682 | public static byte* GetFieldPointer(T obj, string fieldName) where T : class 683 | { 684 | if (obj == null) return null; 685 | int offset = GetFieldOffset(obj.GetType(), fieldName); 686 | if (offset == -1) return null; 687 | return GetRawDataPointer(obj) + offset; 688 | } 689 | 690 | //private static bool SetFieldValue(nint addr, TValue value) 691 | //{ 692 | // if (addr == 0) return false; 693 | // if (value is ValueType) 694 | // { 695 | // int size = UnsafeCore.SizeOf(); 696 | // if (size <= 0) return false; 697 | // byte* valueAddr = GetPointer(ref value); 698 | // Buffer.MemoryCopy((void*)valueAddr, (void*)addr, size, size); 699 | // } 700 | // else 701 | // { 702 | // if (value == null) 703 | // { 704 | // *(IntPtr*)addr = IntPtr.Zero; 705 | // } 706 | // else 707 | // { 708 | // SetValue() 709 | // nint val = GetPointer(value); 710 | // *(IntPtr*)addr = val; 711 | // } 712 | // } 713 | // return true; 714 | //} 715 | 716 | ///// 717 | ///// 设置Object字段的值 718 | ///// 719 | ///// 720 | ///// 721 | ///// 722 | ///// 723 | ///// 724 | ///// 725 | //public static bool SetObjectFieldValue(T obj, string fieldName, TValue value) where T : class 726 | //{ 727 | // IntPtr addr = GetFieldPointer(obj, fieldName); 728 | // if (addr == IntPtr.Zero) return false; 729 | // return SetFieldValue(addr, value); 730 | //} 731 | 732 | ///// 733 | ///// 设置Struct字段的值 734 | ///// 735 | ///// 736 | ///// 737 | ///// 738 | ///// 739 | ///// 740 | ///// 741 | //public static bool SetStructFieldValue(ref T obj, string fieldName, TValue value) where T : struct 742 | //{ 743 | // int offset = GetFieldOffset(typeof(T), fieldName); 744 | // if (offset == -1) return false; 745 | // byte* addr = GetPointer(ref obj) + offset; 746 | // return SetFieldValue(addr, value); 747 | //} 748 | #endregion 749 | 750 | 751 | } 752 | #pragma warning restore CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type 753 | } -------------------------------------------------------------------------------- /UnsafeHelper/UnsafeHelper.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | True 5 | UnsafeHelper 6 | 3.0.0 7 | ilyfairy 8 | C#不安全方法 9 | true 10 | net5.0;net6.0;net7.0 11 | enable 12 | 13 | preview 14 | AnyCPU;x86 15 | True 16 | 17 | 18 | 19 | 20 | false 21 | TARGET_64BIT;$(DefineConstants) 22 | 23 | 24 | TARGET_32BIT;$(DefineConstants) 25 | 26 | 27 | TARGET_64BIT;$(DefineConstants) 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "msbuild-sdks": { 3 | "Microsoft.NET.Sdk.IL": "6.0.0" 4 | } 5 | } --------------------------------------------------------------------------------