DLL中导出函数的声明有两种方式:
1、在函数声明中加上__declspec(dllexport)
//以下内容为 .h 文件中的内容
//向外界提供的端口
extern"C" _declspec(dllexport) int _stdcall Test1(int M, int N);
extern"C" _declspec(dllexport) int _stdcall Test2(int M, int N); //端口函数的声明
int _stdcall Test1(int M, int N);
int _stdcall Test2(int M, int N); class MyClass
{
public:
MyClass();
~MyClass();
public:
int TestFunction1(int M, int N) const; private:
double tmp = 3.1415926;
}; MyClass::MyClass()
{
} MyClass::~MyClass()
{
} int MyClass::TestFunction1(int M, int N) const
{
return M + N;
}
2、采用模块定义(.def) 文件声明,.def文件为链接器提供了有关被链接程序的导出、属性及其他方面的信息。
;以下内容为 .def 文件中的内容
;nativeCPP : 导出 DLL 函数 这句是注释,分号为标志
;LIBRARY语句说明.def文件相应的DLL;
;EXPORTS语句后列出要导出函数的名称。可以在.def文件中的导出函数名后加@n,表示要导出函数的序号为n(在进行函数调用时,这个序号将发挥其作用) LIBRARY "nativeCPP" EXPORT
Test1 @
Test2 @
使用P/Invoke直接调用native C++ Dll里面的函数。(注:此方法只能调用函数,不能调用class)。
C#调用C++导出的方法:
using System;
using System.Runtime.InteropServices; namespace ConsoleApplication_test
{
class Program
{
[DllImport(@"E:\LgsTest\C#_C++\Test_CSharpInvokeCPP_native\Debug\nativeCpp.dll", EntryPoint = "Test1",
SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
static extern int Test1(int M, int N); [DllImport(@"E:\LgsTest\C#_C++\Test_CSharpInvokeCPP_native\Debug\nativeCpp.dll", EntryPoint = "Test2",
SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
static extern int Test2(int M, int N); static void Main(string[] args)
{
int start = Environment.TickCount; //计时开始
int m = ;
int n = ;
int flag = Test1(m, n);
Console.WriteLine("END flag = {0}", flag);
Console.WriteLine(" m = n = {0}", m);
int stop = Environment.TickCount; //计时结束
Console.WriteLine("Seconds1 = {0,10}\n", (double)(stop - start) / ); int start_ = Environment.TickCount; //计时开始
int m_ = ;
int n_ = ;
int flag_ = Test2(m_, n_);
Console.WriteLine("END flag = {0}", flag_);
Console.WriteLine(" m = n = {0}", m_);
int stop_ = Environment.TickCount; //计时结束
Console.WriteLine("Seconds2 = {0,10}", (double)(stop_ - start_) / ); Console.ReadKey();
}
}
}