今天学习了,如何在c++和c#中通过调用自己写的dll文件中的函数来实现一定的功能。可能有些简单,但是有助于初学者学习。
首先分开讲解:
用c++编写dll文件(就是编写c++控制台程序):
// DLL.cpp : 定义 DLL 应用程序的导出函数。 // #include "stdafx.h" extern "C" _declspec(dllexport) int add(int a,int b) { return a+b; } _declspec(dllexport) int sub(int a,int b) { return a-b; }
这里可以看到两个的不同之处,add函数可以被c#调用,可是 sub函数值可以被c++程序调用。
其次编写测试c++调用上面的这个dll文件中的函数:
// DllTest.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<iostream> using namespace std; extern int add(int a,int b); int _tmain(int argc, _TCHAR* argv[]) { int i; i=add(1,2); cout<<"测试i="<<i<<endl; int l; cin >> l; return 0; }
这里需要注意,要把生成的那个.dll和.lib文件一起 放在这个测试程序的.exe同一个文件夹中。
最后编写测试C#调用上面的这个dll中的函数:
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace HardDiskTest { class Program { static void Main(string[] args) { Console.WriteLine("成功复制备份,按任意键关闭窗口............"); Console.ReadKey(); } } class test { [DllImport(@"D:\test\AutoUpgrade\HardDiskTest\lib\dll.dll")] public static extern void SignTestTool(string Filefullpath); } }