问题说明:
因为C++的dll文件是非托管,所以想在C#中使用需要将C++中的dll函数动态调取到想变成的application中,且需要在c#中的unsafe块操作,C#中的参数类型需要根据c#中的格式进行更改 。共两种方法可让c++中的dll文件在c#中使用。
1.C++创建的dll库,需要用静态方法调用;
2.直接使用CLR,生成托管C++dll库;
因为c++和c#之间还是有数据类型的区别的,所以还需要类型转换。
二.动态调用方法
具体会用到这几个知识点。
1.将需要用到的所有函数都封装成unsafe类
因为c#和c++之间架构不同,怕程序溢出所以调用dll文件函数时需要在c#程序中使用unsafe。
①unsafe可以用来修饰类、类的成员函数、类的全局变量,但不能用来修饰类成员函数内的局部变量。
②编译带有unsafe代码的程序也要在“configuration properties>build” 中把允许unsafe代码设为真。
举例:
unsafe class TestDll
{
[DllImport("NTControl.dll", EntryPoint = "Add", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public static extern unsafe System.UInt32 NT_OpenSystem(ref UInt32 systemIndex, string systemLocator, string options);
[DllImport("NTControl.dll", EntryPoint = "Add", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public static extern unsafe System.UInt32 NT_GetNumberOfChannels(System.UInt32 systemIndex, System.UInt32* channels);
[DllImport("NTControl.dll", EntryPoint = "Add", ExactSpelling = false, CallingConvention =