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

}

}

相关推荐
白杨尚青11 分钟前
C++入门篇(十一):string(中)——容量与增删改查:一篇吃透所有常用接口(万字详解)
java·开发语言·c++
老歌老听老掉牙12 分钟前
旅行商问题:从数学模型到 Python 实战
开发语言·python
CC数分13 分钟前
数据可视化入门:用Python把一堆数字变成一张图
开发语言·python·信息可视化·数据分析
java_nnnn13 分钟前
JavaEE进阶-JavaScript初识
开发语言·前端·javascript·java-ee·ecmascript
海天鹰29 分钟前
C#入门:在cmd显示字符
c#
YYYing.31 分钟前
【设计模式系列 (五) 】原型模式
开发语言·后端·设计模式·原型模式·c/c++
重生之小比特34 分钟前
【C++进阶】哈希表实现
开发语言·c++·哈希
m0_380743871 小时前
VisualStudio中OpenCV的创建与配置使用小结
开发语言·c++
凉茶钱1 小时前
【C++】动态内存管理完整解析:从内存划分到 new delete 底层原理
c语言·开发语言·c++·内存管理·动态内存
小七在进步1 小时前
类和对象(五)
java·开发语言·算法