Udostępnij przez


Tworzenie prostej biblioteki Dynamic-Link

Poniższy przykład to kod źródłowy potrzebny do utworzenia prostej biblioteki DLL, Myputs.dll. Definiuje prostą funkcję drukowania ciągów o nazwie myPuts. Biblioteka DLL Myputs nie definiuje funkcji punktu wejścia, ponieważ jest połączona z biblioteką czasu wykonywania języka C i nie ma własnych funkcji inicjowania ani oczyszczania.

Aby skompilować bibliotekę DLL, postępuj zgodnie z instrukcjami zawartymi w dokumentacji dołączonej do narzędzi programistycznych.

Aby zapoznać się z przykładem użycia myPuts, zobacz Używanie Load-Time Dynamic Linking lub Używanie Run-Time Dynamic Linking.

// 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 __cdecl myPuts(LPCWSTR lpszMsg)
{
    DWORD cchWritten;
    HANDLE hConout;
    BOOL fRet;
 
    // Get a handle to the console output device.

    hConout = CreateFileW(L"CONOUT$",
                         GENERIC_WRITE,
                         FILE_SHARE_WRITE,
                         NULL,
                         OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL,
                         NULL);

    if (INVALID_HANDLE_VALUE == hConout)
        return EOF;
 
    // Write a null-terminated string to the console output device.
 
    while (*lpszMsg != L'\0')
    {
        fRet = WriteConsole(hConout, lpszMsg, 1, &cchWritten, NULL);
        if( (FALSE == fRet) || (1 != cchWritten) )
            return EOF;
        lpszMsg++;
    }
    return 1;
}
 
#ifdef __cplusplus
}
#endif