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

}

}

相关推荐
小灰灰搞电子5 小时前
Rust+Slint 实现动态消息提示框源码分享
开发语言·后端·rust
传奇开心果编程7 小时前
【Rust入门知识点学与练】第21课:Trait 进阶 Advanced Traits
开发语言·学习·rust
新时代牛马7 小时前
字符设备驱动完整篇:从 cdev_add、file_operations 到chrdev_open 与排障
开发语言·python
swordbob7 小时前
ReentrantLock 与 AQS 完整学习手册
java·开发语言
淡海水8 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
白山编程大哥8 小时前
Java OutputStreamWriter 详解:从字符到字节的桥梁
java·开发语言·python
shmily麻瓜小菜鸡9 小时前
JavaScript / TypeScript 易踩坑知识点 —— 异步编程类
开发语言·javascript·typescript
七夜zippoe9 小时前
为什么 2026 年每个 Java 团队都该懂 AI Agent
java·开发语言·人工智能
znnnk9 小时前
【Python】GUI 开发从入门到实战(三):PyQt/PySide 进阶之路
开发语言·python·pyqt
Despacito100610 小时前
Java后端性能探查工具速查表
java·开发语言