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

}

}

相关推荐
必须会一定会3 小时前
Agent Plugins 1.0实战:plugin.json、skills、mcp.json目录结构与迁移
开发语言·人工智能·ai编程
St_rive4 小时前
Page Object设计模式
java·开发语言·设计模式
wp123_14 小时前
硬件元器件笔记|IPX8 防水 Type‑C 母座安费诺 124018802112A 与 TONEVEE TY48086‑24A 分析
c语言·开发语言·笔记
wuyk5554 小时前
4.树:一对多的层次数据结构
开发语言·数据结构·stm32·单片机
luj_17685 小时前
桥牌思维启示:系统设计的模块化架构
c语言·开发语言·c++·经验分享·算法
caimouse6 小时前
ReactOS 图形系统分析(16):字符串对象 — STROBJ(string.c)
c语言·开发语言
Aphelios3807 小时前
一次锁内网络IO引发的Tomcat线程池“饿死”事故
java·开发语言·spring boot·elasticsearch·tomcat·网络io阻塞·线程池耗尽
不可求~7 小时前
C++ std::string_view 不是字符串:从悬空引用到安全用法
java·开发语言·c++
90后小陈老师8 小时前
PHP 配置默认值失效排查实录:isset 兜底遇上表单空串回填,首页文案是怎么集体消失的
开发语言·php