博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#代码中插入X86汇编
阅读量:7040 次
发布时间:2019-06-28

本文共 1467 字,大约阅读时间需要 4 分钟。

这两天在看C# SIMD相关的东西, 在爆栈上面搜到一段代码, 表示很震惊, 还是得贴出来…

1 [UnmanagedFunctionPointer(CallingConvention.StdCall)] 2 delegate void VectorAddDelegate(float[] C, float[] B, float[] A, int length); 3  4 [DllImport("kernel32.dll", SetLastError = true)] 5 static extern IntPtr VirtualAlloc( 6     IntPtr lpAddress, UIntPtr dwSize, 7     IntPtr flAllocationType, IntPtr flProtect); 8  9 //This array of bytes has been produced from10 //the SSE assembly version – it is a complete11 //function that accepts four parameters (three12 //vectors and length) and adds the vectors13 14 byte[] sseAssemblyBytes = {15     0x8b, 0x5c, 0x24, 0x10, 0x8b, 0x74, 0x24, 0x0c, 0x8b,16     0x7c, 0x24, 0x08, 0x8b, 0x4c, 0x24, 0x04, 0x31, 0xd2,17     0x0f, 0x10, 0x0c, 0x97, 0x0f, 0x10, 0x04, 0x96, 0x0f,18     0x58, 0xc8, 0x0f, 0x11, 0x0c, 0x91, 0x83, 0xc2, 0x04,19     0x39, 0xda, 0x7f, 0xea, 0xc2, 0x10, 0x00 };20 21 IntPtr codeBuffer = VirtualAlloc(22     IntPtr.Zero, new UIntPtr((uint)sseAssemblyBytes.Length),23     0x1000 | 0x2000, //MEM_COMMIT | MEM_RESERVE24     0x40 //EXECUTE_READWRITE25     );26 27 Marshal.Copy(sseAssemblyBytes, 0, codeBuffer, sseAssemblyBytes.Length);28 29 VectorAddDelegate addVectors = (VectorAddDelegate)30     Marshal.GetDelegateForFunctionPointer(codeBuffer, typeof(VectorAddDelegate));31 //We can now use ‘addVectors’ to add vectors!

这段代码里面的sseAssemblyBytes, 实际上是一段汇编代码, 他先把这段汇编代码拷贝到虚拟内存里面去, 然后设置这块内存可以被执行EXECUTE_READWRITE, 从而在这块内存上创建一个函数指针….

虽然这代码不能移植, 但是感觉还是有一点点屌

转载地址:http://hfxal.baihongyu.com/

你可能感兴趣的文章
linux基本命令
查看>>
IOS开发之UI中的其他小控件
查看>>
据说这些工具可以提高程序员的工作效率
查看>>
IT组织架构的变迁
查看>>
AlarmManager类的应用(实现闹钟功能)
查看>>
自定义实现Hadoop Key-Value
查看>>
Android的数据过滤机制
查看>>
CENTOS流水账0003.2[安装Rails]
查看>>
使用IDEA创建java WebApp(Maven)
查看>>
Hibernate上路_07-数据库乱码解决
查看>>
MySQL 中 localhost 与 127.0.0.1 的区别
查看>>
HTTP中的URL长度限制
查看>>
Python环境搭建、python项目以docker镜像方式部署到Linux
查看>>
玩了一下websocket
查看>>
javascript总结
查看>>
Springboot后台接收前端Date类型
查看>>
仿淘宝选择规格动画效果
查看>>
百度经典算法集合(转)
查看>>
如何合理用网络管理软件灵活管理复杂庞大的网络
查看>>
笨方法学python VI
查看>>