建个网站有收,做游戏网站赚钱吗,上海做推广网站,德城区城乡建设局网站首先从msdn了解到#xff0c;DllImport是用来
将特性化方法由非托管动态链接库 (DLL) 作为静态入口点公开。 从以上语句我们可以理解出三点#xff1a;1.C编写的非托管dll可以通过DllImport引入到C#中#xff1b;2.引入到C#中的只能是C方法#xff08;或者说函数#xff0…首先从msdn了解到DllImport是用来
将特性化方法由非托管动态链接库 (DLL) 作为静态入口点公开。
从以上语句我们可以理解出三点1.C编写的非托管dll可以通过DllImport引入到C#中2.引入到C#中的只能是C方法或者说函数而不能是数据或者说变量3.引入到C#中后只能声明为静态函数msdn关于DllImport属性类的链接http://msdn.microsoft.com/zh-cn/library/system.runtime.interopservices.dllimportattribute(vVS.100).aspxDllImport的其使用格式如下所示[DllImport(compute.dll, EntryPoint FunName, CharSet CharSet.Auto)]public static externint FunName(typevar); 注其引入格式中static和extern是必不可少的接下来主要讲述如何通过DllImport将C类通过dll引入到C#1.生成包含C类的dll源代码如下所示computer.h:#pragma onceclass computer { computer(); public: __declspec(dllexport) int sum(int mem1,int mem2);//计算两个参数之和:mem1mem2 __declspec(dllexport) int sum();//计算两个成员变量之和computer::mem1computer::mem2 __declspec(dllexport) int sub(int mem1,int mem2);//计算两个参数之差:mem1-mem2 __declspec(dllexport) int sub();//计算两个成员变量之差computer::mem1-computer::mem2 __declspec(dllexport) void setmember(int m1,int m2);//设定两个成员静态变量mem1和mem2的值 __declspec(dllexport) int getmember(int index);//index1或2分别读取mem1和mem2的值 private: static int mem1;//只有声明为静态变量才可以在C#中访问修改 static int mem2; }; int computer::mem18;//静态成员初始化 int computer::mem29; 实现代码不在此赘述编译生成dll。2.将生成dll放置到C#工程的debug\bin目录下3.向C#工程中引入此dll并导入编写的类向C#工程中添加新类computer在生成的computer.cs文件中添加代码using System.Runtime.InteropServices;//此语句保证能够调用DllImport编写computer类的代码如下class computer { [DllImport(compute.dll, EntryPoint ?getmembercomputerQAEHHZ, CharSet CharSet.Auto)] public static extern int getmember(intindex); [DllImport(compute.dll,EntryPoint?setmembercomputerQAEXHHZ,CharSetCharSet.Auto)] public static extern void setMember(int m1,intm2); [DllImport(compute.dll, EntryPoint ?sumcomputerQAEHHHZ, CharSet CharSet.Auto)] public static extern int sum(int mem1, intmem2); [DllImport(compute.dll, EntryPoint ?sumcomputerQAEHXZ, CharSet CharSet.Auto)] public static extern int sum(); [DllImport(compute.dll, EntryPoint ?subcomputerQAEHHHZ, CharSet CharSet.Auto)] public static extern int sub(int mem1, intmem2); [DllImport(computer.dll, EntryPoint ?subcomputerQAEHXZ, CharSet CharSet.Auto)] public static extern int sub(); } 具体DllImport的参数属性等请参考如下链接http://blog.csdn.net/jame_peng/article/details/43879064.在主程序中进行验证由于引入的方法都是静态的所以不能通过对象进行调用而只能通过类来调用具体代码如下computer.setMember(4, 5); Console.WriteLine(computer.getmember(1)); Console.WriteLine(computer.getmember(2)); Console.WriteLine(computer.sum()); Console.WriteLine(computer.sum(1,2)); Console.WriteLine(computer.sub(3,1)); 经验证这样的方法是可行的。最后总结一下1.非托管的C函数是可以通过dll经由DllImport引入到C#中不过就变成静态的了2.非托管的C类也可以通过以上方法引入到C#中不过就相当于成为了静态类使用受到了很大限制不可以再定义多个对象了