C# Winform调用win32 C++动态链接库,假设当前有VC++编译器生成的动态库文件testdll.h,testdll.lib和testdll.dll。使用前必须把相应的C++动态库拷贝到工程.exe输出的目录下。
一、.h头文件如下:
#ifdef TESTDLL_EXPORTS
#define TESTDLL_API __declspec(dllexport)
#else
#define TESTDLL_API __declspec(dllimport)
#endif
// 此类是从 testdll.dll 导出的
class TESTDLL_API Ctestdll {
public:
Ctestdll(void);
public:
int Add(int a, int b) {return a+b;}
int Sub(int a, int b) {return a-b;}
int Mul(int a, int b) {return a*b;}
};
extern TESTDLL_API int ntestdll;
TESTDLL_API int fntestdll(void);
二、C#源码如下:
using System;
using System.Runtime.InteropServices;//System.Runtime.InteropServices一般用其DllImport调用windows的DLL函数(Windows API)或调用自用C++写的DLL函数
namespace WindowsFormsApplication2
{
class Ctestdll
{
[DllImport("testdll.dll", EntryPoint = "?Add@Ctestdll@@QAEHHH@Z", CharSet = CharSet.Auto)]//"EntryPoint"的值请使用微软工具DEPENDS.EXE查看。
private static extern int Add(int a, int b);
public int myAdd(int a, int b)
{
return Add(a, b);
}
[DllImport("testdll.dll", EntryPoint = "?Sub@Ctestdll@@QAEHHH@Z", CharSet = CharSet.Auto)]
private static extern int Sub(int a, int b);
public int mySub(int a, int b)
{
return Sub(a, b);
}
[DllImport("testdll.dll", EntryPoint = "?Mul@Ctestdll@@QAEHHH@Z", CharSet = CharSet.Auto)]
private static extern int Mul(int a, int b);
public int myMul(int a, int b)
{
return Mul(a, b);
}
[DllImport("pci9030dll.dll", EntryPoint = "?PMC400_Initial@@YAHXZ", CharSet = CharSet.Auto)]
private static extern int PMC400_Initial();
public int myPMC400_Initial()
{
return PMC400_Initial();
}
}
}