1、C#托管代码与 C+非托管代码互相调用一. C# 中静态调用 C+动态链接1. 建立 VC工程 CppDemo,建立的时候选择 Win32 Console(dll),选择Dll。2. 在 DllDemo.cpp文件中添加这些代码。extern “C“ _declspec(dllexport) int Add(int a,int b)return a+b;3. 编译工程。4. 建立新的 C#工程,选择 Console应用程序,建立测试程序 InteropDemo5. 在 Program.cs中添加引用:using System.Runtime.InteropServices;6. 在 pulic
2、 class Program添加如下代码: using System;using System.Collections.Generic;using System.Text;using System.Runtime.InteropServices;namespace InteropDemoclass ProgramDllImport(“CppDemo.dll“, EntryPoint = “Add“, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)public static extern int Add(in
3、t a, int b); /DllImport请参照MSDNstatic void Main(string args)Console.WriteLine(Add(1, 2);Console.Read();好了,现在您可以测试 Add程序了,是不是可以在 C# 中调用 C+动态链接了,当然这是静态调用,需要将 CppDemo编译生成的 Dll放在 DllDemo程序的Bin目录下二. C# 中动态调用 C+动态链接在第一节中,讲了静态调用 C+动态链接,由于 Dll路径的限制,使用的不是很方便,C#中我们经常通过配置动态的调用托管 Dll,例如常用的一些设计模式:Abstract Factory
4、, Provider, Strategy 模式等等,那么是不是也可以这样动态调用 C+动态链接呢?只要您还记得在 C+中,通过 LoadLibrary, GetProcess, FreeLibrary这几个函数是可以动态调用动态链接的(它们包含在kernel32.dll中),那么问题迎刃而解了,下面我们一步一步实验1. 将 kernel32中的几个方法封装成本地调用类 NativeMethodusing System;using System.Collections.Generic;using System.Text;using System.Runtime.InteropServices;n
5、amespace InteropDemopublic static class NativeMethodDllImport(“kernel32.dll“, EntryPoint = “LoadLibrary“)public static extern int LoadLibrary(MarshalAs(UnmanagedType.LPStr) string lpLibFileName);DllImport(“kernel32.dll“, EntryPoint = “GetProcAddress“)public static extern IntPtr GetProcAddress(int hM
6、odule,MarshalAs(UnmanagedType.LPStr) string lpProcName);DllImport(“kernel32.dll“, EntryPoint = “FreeLibrary“)public static extern bool FreeLibrary(int hModule);2. 使用 NativeMethod类动态读取 C+Dll,获得函数指针,并且将指针封装成 C#中的委托。原因很简单,C#中已经不能使用指针了,如下 int hModule = NativeMethod.LoadLibrary(“c:“CppDemo.dll“);IntPtr i
7、ntPtr = NativeMethod.GetProcAddress(hModule, “Add“);详细请参见代码 using System;using System.Collections.Generic;using System.Text;using System.Runtime.InteropServices;namespace InteropDemoclass Program/DllImport(“CppDemo.dll“, EntryPoint = “Add“, ExactSpelling = false, CallingConvention = CallingConventio
8、n.Cdecl)/public static extern int Add(int a, int b); /DllImport请参照 MSDNstatic void Main(string args)/1. 动态加载 C+ Dllint hModule = NativeMethod.LoadLibrary(“c:CppDemo.dll“);if (hModule = 0) return;/2. 读取函数指针IntPtr intPtr = NativeMethod.GetProcAddress(hModule, “Add“);/3. 将函数指针封装成委托Add addFunction = (Add)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(Add);/4. 测试Console.WriteLine(addFunction(1, 2);Console.Read();/ / 函数指针/ / / / delegate int Add(int a, int b);通过如上两个例子,我们可以在 C#中动态或者静态的调用 C+写的代码了