将《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;

}

}

相关推荐
Wang's Blog6 分钟前
Go-Zero 项目开发22:用户群聊功能的实现与完善
开发语言·golang
a11177626 分钟前
坦克大战3D Three.js 3D (开源项目)
开发语言·javascript·3d
Wang's Blog2 小时前
Go-Zero项目开发24: 基于Bitmap实现群聊消息已读未读
开发语言·后端·golang
code bean3 小时前
【C#】 `Channel<T>` 深度解析:生产者-消费者模式的现代解法
数据结构·c#
吃好睡好便好5 小时前
MATLAB中图像的读取、写入和显示
开发语言·图像处理·学习·计算机视觉·matlab
yaoxin5211235 小时前
476. Java 反射 - 调用方法
java·开发语言
猫头虎6 小时前
什么是ZCode for GLM-5.2?
开发语言·人工智能·python·科技·算法·ai编程·ai写作
吴可可1236 小时前
C# CAD二次开发:合并首尾重合多段线
c#
bksczm6 小时前
Linux之日志和线程池、内存池
java·开发语言
笨蛋不要掉眼泪7 小时前
Java虚拟机:对象复活、引用强度与Stop-The-World
java·开发语言·jvm