C++动态(显式)调用 C++ dll

1、创建DLL新项目Dll1,Dll1.cpp:

1 extern "C" __declspec(dllexport) const char* myfunc()
2 {
3    return "hello,沙奇码";
4 }

生成后,将Dll1.dll置于之后创建控制台程序应用程序同目录下。

2、创建一个C++控制台程序用于调用Dll1.dll测试,ConsoleApplication1.cpp:

 1 #include <Windows.h>
 2 #include <iostream>
 3 using namespace std;
 4 
 5 typedef const char*(*testFunc)();
 6 
 7 void main()
 8 {
 9     HINSTANCE hDll = LoadLibrary("Dll1.dll");
10     testFunc tf = (testFunc)GetProcAddress(hDll,"myfunc");
11     if(!tf)
12     {
13         cout<<"Error"<<endl;
14     }
15     else
16     {
17         cout<<tf()<<endl;
18     }
19     FreeLibrary(hDll);
20     system("pause");
21 }

运行控制台程序,输出 "hello,沙奇码" ~