将《C# 调用非托管程序》一文中最后一种方法修改如下(篇幅原因简化了注释):

/*修改记录

2008-5-11 8:07 曲滨

>> 基本实现预期功能

! 明天进行优化

2008-5-12 15:54 曲滨

E 优化完成

N 加入 NativeCodeHelper 类便于使用

2010-6-17 周振兴

修改兼容性,可在开启DEP及Vista/Win7中运行。

*/

namespace NShellNativeCode

{

using System;

using System.Runtime.InteropServices;

delegate int AddProc(int p1, int p2);

class Program

{

static void Main(string\[\] args)

{

byte\[\] codeBytes = {

0x8B, 0x44, 0x24, 0x08 // mov eax,esp+08h

, 0x8B, 0x4C, 0x24, 0x04 // mov ecx,esp+04h

, 0x03, 0xC1 // add eax,ecx

, 0xC3 // ret

};

/*

上面的字节数组,就是下面函数的本机代码;

int add(int x,int y) {

return x+y;

}

*/

IntPtr handle = IntPtr.Zero;

handle = VirtualAlloc (

IntPtr.Zero,

codeBytes.Length,

MEM_COMMIT | MEM_RESERVE,

PAGE_EXECUTE_READWRITE);

try

{

Marshal.Copy(codeBytes, 0, handle, codeBytes.Length);

AddProc add

= Marshal.GetDelegateForFunctionPointer(handle, typeof(AddProc)) as AddProc;

int r = add(1976, 1);

Console.WriteLine("本机代码返回:{0}", r);

}

finally

{

VirtualFree (handle, 0, MEM_RELEASE);

}

Console.ReadLine();

}

//Windows API

DllImport("Kernel32.dll", EntryPoint = "VirtualAlloc")

public static extern IntPtr VirtualAlloc(IntPtr address, int size, uint allocType, uint protect);

DllImport("Kernel32.dll", EntryPoint = "VirtualFree")

public static extern bool VirtualFree(IntPtr address, int size, uint freeType);

//flags

const uint MEM_COMMIT = 0x1000;

const uint MEM_RESERVE = 0x2000;

const uint PAGE_EXECUTE_READWRITE = 0x40;

const uint MEM_RELEASE = 0x8000;

}

}

相关推荐
辰三1 小时前
统信 UOS + GBase 8s 国产化环境部署实战:从虚拟机到数据库连接完整指南
linux·c#
标致的钢铁侠1 小时前
c# 温故而知新: 线程篇(一)
java·jvm·c#
不知名的老吴1 小时前
浅谈:编程语言中的那些「锁」事(二)
java·开发语言
蜗牛~turbo2 小时前
金蝶云星空的网络控制设置
开发语言·c#·金蝶·erp·云星空·k3 cloud
Reload.2 小时前
GJ航司,验证码网易易盾 JS逆向 纯算轨迹
开发语言·前端·javascript
人道领域2 小时前
【LeetCode刷题日记】贪心算法理论与实战:455.分发饼干最优解
java·开发语言·数据结构·算法·leetcode·贪心算法
xin_yao_xin2 小时前
Conda 环境的 CUDA PATH 配置指南
开发语言·python·conda·cuda
he___H2 小时前
基于LCEL的联想
开发语言·python·langchain
huaqianzkh3 小时前
DevExpress TreeList 右键菜单踩坑复盘:空白区域正常、节点右键弹出控件自带菜单解决方案
c#