调用代码如下:// A simple program that uses LoadLibrary and // GetProcAddress to access myPuts from Myputs.dll. #include <stdio.h> #include <windows.h> extern "C"_declspec(dllimport) typedef int (*MYPROC)(LPTSTR); VOID main(VOID) { HINSTANCE hinstLib; MYPROC ProcAdd; BOOL fFreeResult, fRunTimeLinkSuccess = FALSE; // Get a handle to the DLL module. hinstLib = LoadLibrary(TEXT("dll_msdn")); // If the handle is valid, try to get the function address. if (hinstLib != NULL) { ProcAdd = (MYPROC) GetProcAddress(hinstLib, TEXT("myPuts")); // If the function address is valid, call the function. if (NULL != ProcAdd) { fRunTimeLinkSuccess = TRUE; (ProcAdd) (TEXT("Message via DLL function\n")); } // Free the DLL module. fFreeResult = FreeLibrary(hinstLib); } // If unable to call the DLL function, use an alternative. if (! fRunTimeLinkSuccess) printf("Error\n"); }
dll源码如下:// The myPuts function writes a null-terminated string to// the standard output device. // The export mechanism used here is the __declspec(export)// method supported by Microsoft Visual Studio, but any// other export method supported by your development// environment may be substituted. #include <windows.h> #define EOF (-1) #ifdef __cplusplus // If used by C++ code, extern "C" { // we need to export the C interface#endif __declspec(dllexport) int myPuts(LPTSTR lpszMsg){ DWORD cchWritten; HANDLE hStdout; BOOL fRet; // Get a handle to the standard output device. hStdout = GetStdHandle(STD_OUTPUT_HANDLE); if (INVALID_HANDLE_VALUE == hStdout) return EOF; // Write a null-terminated string to the standard output device. while (*lpszMsg != '\0') { fRet = WriteFile(hStdout, lpszMsg, 1, &cchWritten, NULL); if( (FALSE == fRet) || (1 != cchWritten) ) return EOF; lpszMsg++; } return 1;} #ifdef __cplusplus}#endif