所在的位置: C++ >> C++市场 >> C调用C编写的DLL

C调用C编写的DLL

1把DLL放在C#工程的Debug文件夹跟Release文件夹,我这里是使用X86编译的就放在了这两文件夹

2用DLL查看器Viewdll.exe查看DLL导出的函数如下图

3调用代码如下:

usingSystem.Runtime.InteropServices;//包含DllImport的using指令namespaceTB{publicpartialclassFormTB:Form{//声明外部DLL的函数,这里的DLL函数接口已经从文档得知[DllImport("USER_COM.dll",EntryPoint="OpenCOM",CallingConvention=CallingConvention.Cdecl)]publicstaticexternboolOpenCOM();[DllImport("USER_COM.dll",EntryPoint="Close_COM",CallingConvention=CallingConvention.Cdecl)]publicstaticexternvoidClose_COM();[DllImport("USER_COM.dll",EntryPoint="COM_RX",CallingConvention=CallingConvention.Cdecl)]publicstaticexternintCOM_RX(byte[]RX_buff);[DllImport("USER_COM.dll",EntryPoint="COM_Send",CallingConvention=CallingConvention.Cdecl)]publicstaticexternintCOM_Send(bytecmd,bytedata1,bytedata2);publicFormTB(){InitializeComponent();}//这里以调用DLL里的OpenCOM()为例publicThreadrec;privatevoidFormTB_Load(objectsender,EventArgse){boolop=OpenCOM();//调用DLL的函数Console.WriteLine("op="+op);}}}

如上程序所示,(1)调用dll需要引用命名空间

usingSystem.Runtime.InteropServices;

(2)USER_COM.dll为外部调用的DLL

(3)CallingConvention是指示入口点的调用约定,默认情况下,C和C++使用的Cdecl调用,如果DLL里包含有__stdcall的关键字,CallingConvention要设置成CallingConvention.StdCall

(4)声明外部函数则使用publicstaticextern




转载请注明:http://www.aierlanlan.com/rzdk/2446.html