国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

C#調(diào)用C++Dll

2019-11-14 14:05:56
字體:
供稿:網(wǎng)友

現(xiàn)在項(xiàng)目基本都是旁邊C++的哥們做好dll扔給我,然后我調(diào)用。好久之前晚上down了一份c#調(diào)用c++dll的方法,出處早已經(jīng)遺忘。閑來無事,放上來好了。原作者看到后可以留言,我會(huì)把您鏈接放上的,幫了我很多!!!

  1 using System;  2 using System.Collections.Generic;  3 using System.Linq;  4 using System.Reflection;  5 using System.Reflection.Emit;  6 using System.Runtime.InteropServices;  7 using System.Text;  8   9 namespace TEDS_App 10 { 11     public enum ModePass 12     { 13         ByValue = 0x0001, 14         ByRef = 0x0002 15     } 16     public class FaultFunc 17     { 18         [DllImport("kernel32.dll")] 19         static extern IntPtr LoadLibrary(string lpFileName); 20         [DllImport("kernel32.dll")] 21         static extern IntPtr GetPRocAddress(IntPtr hModule, string lpProcName); 22         [DllImport("kernel32", EntryPoint = "FreeLibrary", SetLastError = true)] 23         static extern bool FreeLibrary(IntPtr hModule); 24         private IntPtr hModule = IntPtr.Zero; 25         private IntPtr farProc = IntPtr.Zero; 26         public void LoadDll(string lpFileName) 27         { 28             hModule = LoadLibrary(lpFileName); 29             if (hModule == IntPtr.Zero) 30             { 31                 throw (new Exception("沒有找到:" + lpFileName + ".")); 32             } 33         } 34         public void LoadDll(IntPtr HMODULE) 35         { 36             if (HMODULE == IntPtr.Zero) 37             { 38                 throw (new Exception("所傳入的函數(shù)庫(kù)模塊的句柄為空")); 39             } 40             hModule = HMODULE; 41         } 42         public void LoadFun(string lpProcName) 43         { 44             if (hModule == IntPtr.Zero) 45             { 46                 throw (new Exception("函數(shù)庫(kù)模塊的句柄為空,確保已進(jìn)行加載dll操作")); 47             } 48             farProc = GetProcAddress(hModule, lpProcName); 49             if (farProc == IntPtr.Zero) 50             { 51                 throw (new Exception("沒有找到:" + lpProcName + "這個(gè)函數(shù)的入口點(diǎn)")); 52             } 53         } 54         public void LoadFun(string lpFileName, string lpProcName) 55         { 56             hModule = LoadLibrary(lpFileName); 57             if (hModule == IntPtr.Zero) 58             { 59                 throw (new Exception("沒有找到:" + lpFileName + ".")); 60             } 61             farProc = GetProcAddress(hModule, lpFileName); 62             if (farProc == IntPtr.Zero) 63             { 64                 throw (new Exception("沒有找到:" + lpProcName + "這個(gè)函數(shù)的入口點(diǎn)")); 65             } 66         } 67         public void UnLoadDll() 68         { 69             FreeLibrary(hModule); 70             hModule = IntPtr.Zero; 71             farProc = IntPtr.Zero; 72         } 73         public object Invoke(object[] ObjArray_Parameter, Type[] TypeArray_parameterType, ModePass[] ModePassArray_Parameter, Type Type_Return) 74         { 75             if (hModule == IntPtr.Zero) 76                 throw (new Exception("函數(shù)庫(kù)模塊的句柄為空,請(qǐng)確保進(jìn)行了LoadLll操作")); 77             if (farProc == IntPtr.Zero) 78                 throw (new Exception("函數(shù)指針為空,請(qǐng)確保已進(jìn)行LoadFun操作")); 79             if (ObjArray_Parameter.Length != ModePassArray_Parameter.Length) 80                 throw (new Exception("參數(shù)個(gè)數(shù)及其傳遞方式的個(gè)數(shù)不匹配")); 81             AssemblyName MyAssemblyName = new AssemblyName(); 82             MyAssemblyName.Name = "InvokeFun"; 83             AssemblyBuilder MyAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(MyAssemblyName, AssemblyBuilderaccess.Run); 84             ModuleBuilder MyModuleBuilder = MyAssemblyBuilder.DefineDynamicModule("InvokeDll"); 85             MethodBuilder MyMethodBuilder = MyModuleBuilder.DefineGlobalMethod("FaultFun", MethodAttributes.Public | MethodAttributes.Static, Type_Return, TypeArray_parameterType); 86             ILGenerator IL = MyMethodBuilder.GetILGenerator(); 87             int i; 88             for (i = 0; i < ObjArray_Parameter.Length; i++) 89             { 90                 switch (ModePassArray_Parameter[i]) 91                 { 92                     case ModePass.ByValue: 93                         IL.Emit(OpCodes.Ldarg, i); 94                         break; 95                     case ModePass.ByRef: 96                         IL.Emit(OpCodes.Ldarga, i); 97                         break; 98                     default: 99                         throw (new Exception("" + (i + 1).ToString() + "個(gè)參數(shù)沒有給定正確的傳遞方式"));100                 }101             }102             if (IntPtr.Size == 4)103             {104                 IL.Emit(OpCodes.Ldc_I4, farProc.ToInt32());105             }106             else if (IntPtr.Size == 8)107             {108                 IL.Emit(OpCodes.Ldc_I8, farProc.ToInt64());109             }110             else111             {112                 throw new PlatformNotSupportedException();113             }114             IL.EmitCalli(OpCodes.Calli, CallingConvention.StdCall, Type_Return, TypeArray_parameterType);115             IL.Emit(OpCodes.Ret);116             MyModuleBuilder.CreateGlobalFunctions();117             MethodInfo MyMethodInfo = MyModuleBuilder.GetMethod("FaultFun");118             return MyMethodInfo.Invoke(null, ObjArray_Parameter);119         }120         public object Invoke(IntPtr IntPtr_Function, object[] ObjArray_Parameter, Type[] TypeArray_ParameterType, ModePass[] ModePassArray_Parameter, Type Type_Return)121         {122             if (hModule == IntPtr.Zero)123                 throw (new Exception("函數(shù)庫(kù)模塊的句柄為空,請(qǐng)確保已進(jìn)行LoadDll操作"));124             if (IntPtr_Function == IntPtr.Zero)125                 throw (new Exception("函數(shù)指針I(yè)ntPtr_Function為空"));126             farProc = IntPtr_Function;127             return Invoke(ObjArray_Parameter, TypeArray_ParameterType, ModePassArray_Parameter, Type_Return);128         }129     }130 131 }

一直以來,對(duì)于C++程序員報(bào)以崇高的敬意。。。一直覺得他們屌屌的,哈哈。

調(diào)用方式如下:

1 PlusFunction.LoadDll(@"C:/win32dll.dll");//PlusFunction為調(diào)用類的實(shí)例2 PlusFunction.LoadFun("MyFun");3 byte[] a = File.ReadAllBytes(@"E:/19-bw/19-73.jpg");4 object[] Parameters = new object[] {a}; // 實(shí)參為a5 Type[] ParameterTypes = new Type[] { typeof(byte[])}; // 實(shí)參類型為byte[]6 ModePass[] themode = new ModePass[] {ModePass.ByValue}; // 傳送方式為值傳7 Type Type_Return = typeof(int); // 返回類型為int8 ret = (int)PlusFunction.Invoke(Parameters, ParameterTypes, themode, Type_Return);

其實(shí),c++與c#主要的就是數(shù)據(jù)類型的對(duì)應(yīng)了。簡(jiǎn)單點(diǎn)的還好說,稍微復(fù)雜的各種麻煩。。。關(guān)鍵是不好調(diào)試。

下面舉些我用到的例子,以后遇到其他的再補(bǔ)充。日積月累- -

 1 c++                                    c# 2 char*                                char[](string.tochararray) 3 byte*                                 byte[] 4 int                                    int 5 int*                                    int[] 6 結(jié)構(gòu)體 7 c++ 8 typedef struct SRectChange_TAG 9 {10     //NV_RECT rect;11     int x;//左上角x軸坐標(biāo)12     int y;//左上角y軸坐標(biāo)13     int width;//14     int height;//15     int degree;//報(bào)錯(cuò)級(jí)別;1最低,目前暫時(shí)設(shè)定3級(jí)16 }17 SRectChange;18 c#19 [StructLayout(LayoutKind.Sequential)]20 public struct SRectChange21 {22     public int x;23     public int y;24     public int width;25     public int height;26     public int degree;27 }28 結(jié)構(gòu)體傳遞29 [DllImport("win32dll.dll", EntryPoint = "MyFun", CallingConvention = CallingConvention.Cdecl)]30 public static extern int MyFun(ref SRectChange rect, char[] str, char[] str2);   31 c++結(jié)構(gòu)體32 typedef struct      33 {    34     int osVersion;    35     int majorVersion;    36     int minorVersion;    37     int buildNum;    38     int platFormId;    39     char szVersion[128];    40 }OSINFO; 41 c#42 // OSINFO定義  43 [StructLayout(LayoutKind.Sequential)]  44 public struct OSINFO  45 {  46     public int osVersion;  47     public int majorVersion;  48     public int minorVersion;  49     public int buildNum;  50     public int platFormId;  51     [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]  52     public string szVersion;  53 }  54 55 結(jié)構(gòu)體數(shù)組傳遞56 c#代碼57 [DllImport("win32dll.dll", EntryPoint = "MyFun", CallingConvention = CallingConvention.Cdecl)]58 public static extern int MyFun(IntPtr p, char[] str, char[] str2);  59 數(shù)組傳指針60 char[] newpic = ("123123123123").ToCharArray();61 char[] oldpic = ("231231234123").ToCharArray();62 SRectChange[] rects = new SRectChange[5];63 for (int i = 0; i < rects.Length; i++)64 {65     rects[i] = new SRectChange();66 }67 IntPtr[] ptArr = new IntPtr[1];68 ptArr[0] = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SRectChange)) * 5); //分配包含兩個(gè)元素的數(shù)組  69 IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SRectChange)));70 Marshal.Copy(ptArr, 0, pt, 1); //拷貝指針數(shù)組71 MyFun(pt, newpic, oldpic);72 for (int i = 0; i < 5; i++)73 {74     rects[i] = (SRectChange)Marshal.PtrToStructure((IntPtr)(pt.ToInt32() + i * Marshal.SizeOf(typeof(SRectChange))), typeof(SRectChange));75     Console.WriteLine("x:{0} y:{1}", rects[i].x, rects[i].y);76 }

還說那句話:種一棵樹最好的時(shí)間是十年前,其次是現(xiàn)在。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 瑞丽市| 娄烦县| 新邵县| 芮城县| 屏南县| 旺苍县| 望城县| 卢龙县| 舟曲县| 浙江省| 府谷县| 巴东县| 稻城县| 湘阴县| 杨浦区| 佛坪县| 根河市| 镇安县| 中宁县| 民县| 壶关县| 柳林县| 大埔县| 崇信县| 宁安市| 海丰县| 竹溪县| 长顺县| 彭阳县| 新源县| 嘉荫县| 泰安市| 九江市| 寿光市| 东阳市| 安西县| 凤庆县| 无极县| 新邵县| 甘南县| 贵溪市|