C#托管代码与C++非托管代码互相调用实例.docx
上传人:sy****28 上传时间:2024-09-14 格式:DOCX 页数:4 大小:17KB 金币:16 举报 版权申诉
预览加载中,请您耐心等待几秒...

C#托管代码与C++非托管代码互相调用实例.docx

C#托管代码与C++非托管代码互相调用实例.docx

预览

在线预览结束,喜欢就下载吧,查找使用更方便

16 金币

下载此文档

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

C#托管代码与C++非托管代码互相调用一.C#中静态调用C++动态链接1.建立VC工程CppDemo,建立的时候选择Win32Console(dll),选择Dll。2.在DllDemo.cpp文件中添加这些代码。Codeextern"C"__declspec(dllexport)intAdd(inta,intb){returna+b;}3.编译工程。4.建立新的C#工程,选择Console应用程序,建立测试程序InteropDemo5.在Program.cs中添加引用:usingSystem.Runtime.InteropServices;6.在pulicclassProgram添加如下代码:CodeusingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Runtime.InteropServices;namespaceInteropDemo{classProgram{[DllImport("CppDemo.dll",EntryPoint="Add",ExactSpelling=false,CallingConvention=CallingConvention.Cdecl)]publicstaticexternintAdd(inta,intb);//DllImport请参照MSDNstaticvoidMain(string[]args){Console.WriteLine(Add(1,2));Console.Read();}}}好了,现在您可以测试Add程序了,是不是可以在C#中调用C++动态链接了,当然这是静态调用,需要将CppDemo编译生成的Dll放在DllDemo程序的Bin目录下二.C#中动态调用C++动态链接在第一节中,讲了静态调用C++动态链接,由于Dll路径的限制,使用的不是很方便,C#中我们经常通过配置动态的调用托管Dll,例如常用的一些设计模式:AbstractFactory,Provider,Strategy模式等等,那么是不是也可以这样动态调用C++动态链接呢?只要您还记得在C++中,通过LoadLibrary,GetProcess,FreeLibrary这几个函数是可以动态调用动态链接的(它们包含在kernel32.dll中),那么问题迎刃而解了,下面我们一步一步实验1.将kernel32中的几个方法封装成本地调用类NativeMethodCodeusingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Runtime.InteropServices;namespaceInteropDemo{publicstaticclassNativeMethod{[DllImport("kernel32.dll",EntryPoint="LoadLibrary")]publicstaticexternintLoadLibrary([MarshalAs(UnmanagedType.LPStr)]stringlpLibFileName);[DllImport("kernel32.dll",EntryPoint="GetProcAddress")]publicstaticexternIntPtrGetProcAddress(inthModule,[MarshalAs(UnmanagedType.LPStr)]stringlpProcName);[DllImport("kernel32.dll",EntryPoint="FreeLibrary")]publicstaticexternboolFreeLibrary(inthModule);}}2.使用NativeMethod类动态读取C++Dll,获得函数指针,并且将指针封装成C#中的委托。原因很简单,C#中已经不能使用指针了,如下inthModule=NativeMethod.LoadLibrary(@"c:"CppDemo.dll");IntPtrintPtr=NativeMethod.GetProcAddress(hModule,"Add");详细请参见代码CodeusingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Runtime.InteropServices;namespaceInteropDemo{classProgram{//[DllImport("CppDemo.dll",EntryPoint="Add",ExactSpelling=false,Cal