C#调用C/C++开发的dll方法

分类:.Net知识问答| 发布:camnprbubuol| 查看: | 发表时间:2011/3/24

方法一:P/Invoke调用非托管代码的方法
[DllImport("camnpr.dll")]
static extern Int32 Jie(Int32 arg);

方法二:LoadLibrary动态调用
[DllImport("Kernel32")] 
publicstaticexternintGetProcAddress(inthandle,Stringfuncname); 
[DllImport("Kernel32")] 
publicstaticexternintLoadLibrary(Stringfuncname); 
[DllImport("Kernel32")] 
publicstaticexternintFreeLibrary(inthandle);

方法三:反射调用
1  /// <summary>
2         /// 获取DLL中函数
3         /// </summary>
4         /// <param name="dllName">DLL文件的名字(路径),如果在PATH环境变量下或当期目录中则可以直接指定DLL的名字,否则应包括其路径信息</param>
5         /// <param name="methodName">函数名字</param>
6         /// <param name="returnType">返回类型</param>
7         /// <param name="paramTypes">参数类型,如果无参数则为null</param>
8         /// <param name="declareCallingConvertions">生成的函数的调用约定</param>
9         /// <param name="nativeCallingConvertions">DLL函数的调用约定</param>
10         /// <param name="nativeCharSet">字符集</param>
11         /// <returns>代表指定DLL中指定函数的MethodInfo,是一个静态方法</returns>
12          public static MethodInfo GetMethodInfoInDll(string dllName, string methodName, 
13             Type returnType, Type[] paramTypes,
14             CallingConventions declareCallingConvertions,
15             System.Runtime.InteropServices.CallingConvention nativeCallingConvertions,
16             System.Runtime.InteropServices.CharSet nativeCharSet)
17         {
18             AssemblyName assemblyName=new AssemblyName("Assembly"+Environment.TickCount);
19             AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.Run);
20             ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);
21             
22             MethodInfo method = moduleBuilder.DefinePInvokeMethod(methodName, dllName,
23                 MethodAttributes.PinvokeImpl | MethodAttributes.Static | MethodAttributes.Public,
24                 declareCallingConvertions, returnType, paramTypes,
25                 nativeCallingConvertions, nativeCharSet);
26 
27 
28             moduleBuilder.CreateGlobalFunctions();
29 
30             MethodInfo methodInfo = moduleBuilder.GetMethod(methodName,paramTypes);
31 
32             return methodInfo;
33            
34         }

365据说看到好文章不转的人,服务器容易宕机
原创文章如转载,请注明:转载自郑州网建-前端开发 http://camnpr.com/
本文链接:http://camnpr.com/net-wiki/252.html