分享

C#调用非托管程序5种方式

 Mike Lee 2010-09-29

C#调用非托管程序5种方式

 

1、COM调用
COM应该是非托管组件重用最重要的方式,特别是调用微软的COM组件。
可以用VS添加引用的方式自动生成包装类,也可以用Tlbimp.exe实用工具包装COM对象生成包装类。
COM对象需要在本机注册,这个程序部署带来一定的麻烦,如果调用简单的功能,包装COM有点大材小用。
如果只简单的调用非托管函数,可以用接下来介绍的DllImprot等方式。

  1. using System;  
  2. using OLEPRNLib;  
  3.  
  4. namespace PrinterStatus  
  5. {  
  6.     class Class1  
  7.     {  
  8.         [STAThread]  
  9.         static void Main(string[] args)  
  10.         {  
  11.             string[] ErrorMessageText = new string[8];  
  12.  
  13.             ErrorMessageText[0] = "service requested";  
  14.             ErrorMessageText[1] = "offline";  
  15.             ErrorMessageText[2] = "paper jammed";  
  16.             ErrorMessageText[3] = "door open";  
  17.             ErrorMessageText[4] = "no toner";  
  18.             ErrorMessageText[5] = "toner low";  
  19.             ErrorMessageText[6] = "out of paper";  
  20.             ErrorMessageText[7] = "low paper";  
  21.  
  22.             int DeviceID = 1;  
  23.             int Retries = 1;  
  24.             int TimeoutInMS = 2000;  
  25.             string CommunityString = "public";  
  26.             string IPAddressOfPrinter = "10.3.0.93";  
  27.  
  28.             // Create instance of COM object  
  29.             OLEPRNLib.SNMP snmp = new OLEPRNLib.SNMP();  
  30.  
  31.             // Open the SNMP connect to the printer  
  32.             snmp.Open(IPAddressOfPrinter, CommunityString, Retries, TimeoutInMS);  
  33.  
  34.             // The actual Warning/Error bits  
  35.             uint WarningErrorBits = snmp.GetAsByte(String.Format("25.3.5.1.2.{0}", DeviceID));  
  36.  
  37.             // The actual Status  
  38.             uint StatusResult = snmp.GetAsByte(String.Format("25.3.2.1.5.{0}", DeviceID));  
  39.  
  40.             // uint Result2 = snmp.GetAsByte(String.Format("25.3.5.1.1.{0}", DeviceID));  
  41.  
  42.             string Result1Str = "";  
  43.             switch (StatusResult)  
  44.             {  
  45.                 case 2: Result1Str = "OK";  
  46.                     break;  
  47.                 case 3: Result1Str = "Warning: ";  
  48.                     break;  
  49.                 case 4: Result1Str = "Being Tested: ";  
  50.                     break;  
  51.                 case 5: Result1Str = "Unavailable for any use: ";  
  52.                     break;  
  53.                 default: Result1Str = "Unknown Status Code : " + StatusResult;  
  54.                     break;  
  55.             }  
  56.  
  57.             string Str = "";  
  58.             if ((StatusResult == 3 || StatusResult == 5))  
  59.             {  
  60.                 int Mask = 1;  
  61.                 int NumMsg = 0;  
  62.                 for (int i = 0; i < 8; i++)  
  63.                 {  
  64.                     if ((WarningErrorBits & Mask) == Mask)  
  65.                     {  
  66.                         if (Str.Length > 0)  
  67.                             Str += ", ";  
  68.                         Str += ErrorMessageText[i];  
  69.                         NumMsg = NumMsg + 1;  
  70.                     }  
  71.                     Mask = Mask * 2;  
  72.                 }  
  73.             }  
  74.             Console.WriteLine(Result1Str + Str);  
  75.         }  
  76.     }  


2、DllImport
DllImport是在"System.Runtime.InteropServices"命名空间中定义的特性。

  1. [DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "MessageBox")]  
  2. public static extern int InvokeMessageBox(IntPtr hWnd, String text, String caption, uint type);  
  3.  
  4. static void Main()  
  5. {  
  6.     InvokeMessageBox(new IntPtr(0), "对话框内容""对话框标题", 0);  


3、加载非托管动态链接库
Win32中,有个LoadLibrary(string file)函数,加载动态链接库;GetProcAddress函数动态调用导出函数。
.NET类库的 Marshal.GetDelegateForFunctionPointer 方法能将非托管函数指针转换为委托。

  1. public delegate int MsgBox(int hwnd,string msg,string cpp,int ok);  
  2. [DllImport("Kernel32")]  
  3. public static extern int GetProcAddress(int handle, String funcname);  
  4. [DllImport("Kernel32")]  
  5. public static extern int LoadLibrary(String funcname);  
  6. [DllImport("Kernel32")]  
  7. public static extern int FreeLibrary(int handle);  
  8.  
  9. private static Delegate GetAddress(int dllModule, string functionname, Type t)  
  10. {  
  11.     int addr = GetProcAddress(dllModule, functionname);  
  12.     if (addr == 0)  
  13.         return null;  
  14.     else  
  15.         return Marshal.GetDelegateForFunctionPointer(new IntPtr(addr), t);  
  16. }  
  17.  
  18. private void button1_Click(object sender, EventArgs e)  
  19. {  
  20.     int huser32 = 0;  
  21.     huser32 = LoadLibrary("user32.dll");          
  22.     MsgBox mymsg = (MsgBox)GetAddress(huser32, "MessageBoxA"typeof(MsgBox));  
  23.     mymsg(this.Handle.ToInt32(), txtmsg.Text, txttitle.Text , 64);  
  24.     FreeLibrary(huser32);  


4、DynamicMethod
可以使用 DynamicMethod 类在运行时生成和执行方法,而不必生成动态程序集和动态类型来包含该方法。动态方法是生成和执行少量代码的最有效方式。

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using Zealic.Windows;  
  5.  
  6. namespace ConsoleApplication1  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             //测试1  
  13.             DynamicLibrary hilib = new DynamicLibrary("hi.dll");  
  14.             NativeMethodBuilder hiBuilder = new NativeMethodBuilder();  
  15.             NativeMethod method = hiBuilder.MakeMethod(hilib, "func");  
  16.             Console.WriteLine("请关闭弹出的对话框 'Hille'");  
  17.             method.Invoke();  
  18.             hilib.Free();  
  19.  
  20.             //测试2  
  21.             DynamicLibrary krnlib = new DynamicLibrary("kernel32.dll");  
  22.             NativeMethodBuilder beepBuilder = new NativeMethodBuilder();  
  23.             beepBuilder.ParameterLength = 2;  
  24.             beepBuilder.SetParameterInfo(0, typeof(int));  
  25.             beepBuilder.SetParameterInfo(1, typeof(int));  
  26.             method = beepBuilder.MakeMethod(krnlib,"Beep");  
  27.             Console.WriteLine("听,你的机器在尖叫!");  
  28.             method.Invoke(1000, 1000);  
  29.             Console.WriteLine("按任意键退出!");  
  30.             Console.ReadKey(true);  
  31.         }  
  32.     }  


5、直接调用执行机器码
机器码是最原始的程序代码,或称指令,把这些指令装载到内存,Marshal.GetDelegateForFunctionPointer方法转换为对应的委托,调用即可。

  1. /*  
  2.       
  3.     执行调用本机代码、汇编代码 shell Native Code  
  4.  
  5.     解释  
  6.         本例中 IntPtr 其实是相当于 C 语言中的 (void *) 指向任何类型的指针,  
  7.             就是一个地址 32 位系统就是个 Int32,本例相当与一个函数指针  
  8.  
  9.     核心技术流程  
  10.         变量:  
  11.             【本机代码字节数组】 byte[] codeBytes ; 一段加法本机代码  
  12.             【函数指针】 IntPtr handle ; 指向本机函数开始地址的变量  
  13.         流程:  
  14.               
  15.         >> 给 【函数指针】划分非托管内存 ; 使用 Marshal.AllocHGlobal(codeBytes.Length)  
  16.                 划分大小等同于本机代码字节总数    因为函数本身还不存在于内存中所以先开辟一块内存;  
  17.                 以便放置函数。  
  18.                   
  19.         >> 将 【本机代码字节数组】中的字节写入 【函数指针】 ;  
  20.                 Marshal.Copy(codeBytes,0,handle,codeBytes.Length);  
  21.  
  22.           
  23.         >> 使用 Marshal.GetDelegateForFunctionPointer 【函数指针】 强制转换为托管委托 DelegateAdd;  
  24.                 因为这时 handle 内的字节数组已经是内存中的一段本机方法的代码  
  25.                 handle 的“起始地址”就相当于一个“本机函数的入口地址”  
  26.                 所以可以成功转换为对应的委托  
  27.  
  28.         >> 调用 委托 ;  
  29.  
  30.         >> 释放本机句柄;Marshal.FreeHGlobal(this._handle);  
  31.  
  32. 修改记录  
  33.     2008-5-11 8:07 曲滨  
  34.         >> 基本实现预期功能  
  35.         [!] 明天进行优化  
  36.  
  37.     2008-5-12 15:54 曲滨  
  38.         [E] 优化完成  
  39.         [N] 加入 NativeCodeHelper 类便于使用  
  40. */  
  41. namespace NShellNativeCode  
  42. {  
  43.     using System;  
  44.     using System.Collections.Generic;  
  45.     using System.Text;  
  46.     using System.Runtime.InteropServices;  
  47.     using System.IO;  
  48.     using System.Diagnostics;  
  49.     using System.Reflection;  
  50.       
  51.     delegate int AddProc(int p1, int p2);  
  52.     class Program  
  53.     {  
  54.           
  55.  
  56.         static void Main(string[] args)  
  57.         {  
  58.               
  59.             //一段加法函数本机代码;后面注释是给会 asm 看官看的  
  60.             //笔者本身也不是太明白汇编,简单的 10行8行的还可以  
  61.               
  62.             byte[] codeBytes = {  
  63.                   0x8B, 0x44, 0x24, 0x08    // mov eax,[esp+08h]  
  64.                 , 0x8B, 0x4C, 0x24, 0x04    // mov ecx,[esp+04h]  
  65.                 , 0x03, 0xC1                // add    eax,ecx  
  66.                 , 0xC3                        // ret  
  67.                 };  
  68.                           
  69.             /*  
  70.             上面的字节数组,就是下面函数的本机代码;  
  71.             int add(int x,int y) {  
  72.                 return x+y;  
  73.             }  
  74.               
  75.             */  
  76.  
  77.             IntPtr handle = IntPtr.Zero;  
  78.             handle = Marshal.AllocHGlobal(codeBytes.Length);  
  79.             try  
  80.             {  
  81.  
  82.                 Marshal.Copy(codeBytes, 0, handle, codeBytes.Length);  
  83.                                   
  84.                 AddProc add  
  85.                    = Marshal.GetDelegateForFunctionPointer(handle, typeof(AddProc)) as AddProc;  
  86.                   
  87.                 int r = add(1976, 1);  
  88.  
  89.                 Console.WriteLine("本机代码返回:{0}", r);  
  90.  
  91.  
  92.             }  
  93.             finally  
  94.             {  
  95.                 Marshal.FreeHGlobal(handle);  
  96.             }  
  97.               
  98.             //本演示内包含的已经封装好的 本机字节代码,转换委托通用类  
  99.             //打开注释就可以用了;  
  100.               
  101.             /*  
  102.             using (NativeCodeHelper helper = new NativeCodeHelper(codeBytes))  
  103.             {  
  104.                 AddProc add = helper.ToDelegate<AddProc>();  
  105.                 Type t =  add.Method.DeclaringType;  
  106.                 int r = add(1976,1);  
  107.                 Console.WriteLine("本机代码返回:{0}",r);  
  108.             }  
  109.             */  
  110.                       
  111.               
  112.             //Console.ReadLine();  
  113.         }      
  114.               
  115.           
  116.     }  
  117.  
  118. /*  
  119.     结束语  
  120.         已知问题  
  121.             1)在操作系统打开 DEP 保护的情况下,这类代码会不灵;  
  122.                 我没有测试,有兴趣的可以试验一下,估计是不会好用的;  
  123.               
  124.             2)如果要在 本机代码 中调用 Win API 函数,因为在不同系统不同版本中  
  125.                 Win API 的地址是不同的;  
  126.                 要有一些编写 shell code 能力于黑客技术关系密切这里不做详细描述  
  127.       
  128.         本文技术的适用范围  
  129.             >> 遗留系统,C/C++ 的某些算法、尤其汇编形式的是如果懒的改成.net 可以直接吧二进制copy  
  130.                 出来直接调用、不过需要C/VC、反汇编、汇编有点了解要不没法Copy;  
  131.  
  132.             >> 有些代码不想被反编译,给破解者增加些破解难度、郁闷有可能会改你代码的人  
  133.                 实用性有多少看官自己感觉吧,因为技术这东西是相对的  
  134.                 如果你的程序中到处都是这类代码是很难维护的,就是熟悉汇编的人  
  135.                 这种东西多了也很郁闷的、本机代码远比汇编难看的多    
  136.  
  137.             >> 忽悠小朋友  
  138.                 把我的代码直接copy倒你的项目里,一点都不改,要算int加法的时候都这么用  
  139.                 如果有小朋友看见一定会感觉你很 Cool  
  140.           
  141.         重要声明:  
  142.             这种本机代码方式如果应用倒真实项目中一定要项目负责人的同意的情况下,否则出现  
  143.         任何人事问题,或刑事问题与本文作者无关;  
  144.             如  
  145.                 >> 在真实项目中使用本文技术,在代码中坠入逻辑炸弹者;  
  146.                 >> 在真实项目中使用本文技术,拒不上缴本机字节代码对应的源代码者;  
  147.                 >> 在真实项目或共享软件中,捆绑病毒代码者;  
  148.           
  149. */  
  150.  
  151.     /// <summary>  
  152.     /// 用于将本机代码 byte 数组转换为 .net 委托  
  153.     /// </summary>  
  154.     /// <remarks>  
  155.     /// 实现了 IDisposable 使用了非托管资源 使用时不要忘记释放  
  156.     /// </remarks>  
  157.     public class NativeCodeHelper:IDisposable  
  158.     {  
  159.           
  160.         private bool _disposed = false;  
  161.         private byte[] _codeBytes = {};  
  162.         private IntPtr _handle = IntPtr.Zero;  
  163.           
  164.         public NativeCodeHelper(byte[] codeBytes)  
  165.         {  
  166.              this._codeBytes =  codeBytes;  
  167.         }  
  168.           
  169.         /// <summary>  
  170.         /// 把byte数字转换为本机类型的指针 主要处理 this._handle  
  171.         /// </summary>  
  172.         private void CreateHandle()  
  173.         {  
  174.             if (_handle == IntPtr.Zero)  
  175.             {  
  176.                 _handle = Marshal.AllocHGlobal( this._codeBytes.Length);  
  177.                 Marshal.Copy(_codeBytes, 0, _handle, _codeBytes.Length);  
  178.             }          
  179.         }  
  180.         /// <summary>  
  181.         /// 转换为指定的委托  
  182.         /// </summary>  
  183.         /// <typeparam name="T"></typeparam>  
  184.         /// <returns></returns>  
  185.         public T ToDelegate<T>() where T:class  
  186.         {  
  187.             this.CreateHandle();  
  188.               
  189.             //把指针转换为 委托方法  
  190.             T result = Marshal.GetDelegateForFunctionPointer(_handle, typeof(T)) as T;              
  191.               
  192.             return result;  
  193.  
  194.         }  
  195.           
  196.         #region IDisposable 成员  
  197.           
  198.         ~NativeCodeHelper()  
  199.         {  
  200.             Dispose(false);  
  201.         }  
  202.           
  203.         public void Dispose()  
  204.         {  
  205.             Dispose(true);          
  206.             GC.SuppressFinalize(this);  
  207.  
  208.         }  
  209.  
  210.           
  211.           
  212.         private void Dispose(bool disposing)  
  213.         {  
  214.             if (disposing)  
  215.             {  
  216.                 //给调用者忘记 Dispose 释放的提示  
  217.                 MethodBase mb = System.Reflection.MethodBase.GetCurrentMethod();  
  218.                 Type t = mb.DeclaringType;  
  219.                   
  220.                 Trace.WriteLine("not Dispose"  
  221.                 , "" + t + "." + mb );  
  222.             }  
  223.               
  224.               
  225.             if (!this._disposed)  
  226.             {  
  227.                 if (disposing)  
  228.                 {  
  229.                     //释放.net 需要 Dispose 的对象                      
  230.                 }  
  231.  
  232.                 Marshal.FreeHGlobal(this._handle);  
  233.                 _handle = IntPtr.Zero;  
  234.             }  
  235.             _disposed = true;  
  236.         }          
  237.  
  238.         #endregion  
  239.     }  
  240. }  

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多