欢迎来到天天文库
浏览记录
ID:37914447
大小:50.50 KB
页数:7页
时间:2019-06-02
《C#托管代码与C++非托管代码互相调使用》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、C++调dllHINSTANCEhDllInst=LoadLibrary("c:\msg.dll");if(hDllInst){typedefint(WINAPI*MSGBOX)(char*,char*);MSGBOXMsgBox=NULL;MsgBox=(MSGBOX)GetProcAddress(hDllInst,"MsgBox");if(MsgBox){//这里可以做你想做的事了}FreeLibrary(hDllInst);}如果想什么地方都能调用MsgBox,那么可以把函数指针定义成全局变量【转】C#托管代码与C++非托管代码互相调使用2011-08-
2、0210:52转载自分享最终编辑maydaygmailC#托管代码与C++非托管代码互相调使用一(C#调使用C++代码&.net代码安全) 在最近的项目中,牵涉到项目源代码保密问题,由于代码是C#写的,容易被反编译,因此决定抽取核心算法部分使用C++编写,C++到目前为止好像还不能被很好的反编译,当然如果你是反汇编高手的话,也许还是有可能反编译。这样一来,就涉及C#托管代码与C++非托管代码互相调用,于是调查了一些资料,顺便与大家分享一下 一.C#中静态调用C++动态链接 1.建立VC工程CppDemo,建立的时候选择Win32Console(dll),选
3、择Dll。 2.在DllDemo.cpp文件中添加这些代码。extern"C"__declspec(dllexport)intAdd(inta,intb){ returna+b;} 3.编译工程。 4.建立新的C#工程,选择Console应用程序,建立测试程序InteropDemo 5.在Program.cs中添加引用:usingSystem.Runtime.InteropServices; 6.在pulicclassProgram添加如下代码:usingSystem;usingSystem.Collections.Generic;usin
4、gSystem.Text;usingSystem.Runtime.InteropServices;namespaceInteropDemo{ classProgram { [DllImport("CppDemo.dll",EntryPoint="Add",ExactSpelling=false,CallingConvention=CallingConvention.Cdecl)] publicstaticexternintAdd(inta,intb);//DllImport请参照MSDN staticvoidMain(
5、string[]args) { Console.WriteLine(Add(1,2)); Console.Read(); } }} 好了,现在您可以测试Add程序了,是不是可以在C#中调用C++动态链接了,当然这是静态调用,需要将CppDemo编译生成的Dll放在DllDemo程序的Bin目录下 二.C#中动态调用C++动态链接 在第一节中,讲了静态调用C++动态链接,由于Dll路径的限制,使用的不是很方便,C#中我们经常通过配置动态的调用托管Dll,例如常用的一些设计模式:Abstrac
6、tFactory,Provider,Strategy模式等等,那么是不是也可以这样动态调用C++动态链接呢?只要您还记得在C++中,通过LoadLibrary,GetProcess,FreeLibrary这几个函数是可以动态调用动态链接的(它们包含在kernel32.dll中),那么问题迎刃而解了,下面我们一步一步实验 1. 将kernel32中的几个方法封装成本地调用类NativeMethodusingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Runtime.Int
7、eropServices;namespaceInteropDemo{ publicstaticclassNativeMethod { [DllImport("kernel32.dll",EntryPoint="LoadLibrary")] publicstaticexternintLoadLibrary( [MarshalAs(UnmanagedType.LPStr)]stringlpLibFileName); [DllImport("kernel32.dll",EntryPoint="GetPro
8、cAddress")]
此文档下载收益归作者所有