Cayoot
Cayoot

Reputation: 61

Understanding Asynchronous / Overlapped IO

I am learning about Asynchronous / Overlapped IO in windows. I have written the following code, but it doesn't compile. Where is my mistake? I don't know why we need to call something as FileIoCompletionRoutine and how should I define it?

#include <windows.h>
#include <iostream>

VOID WINAPI FileIOCompletionRoutine(DWORD, DWORD, LPOVERLAPPED);
HANDLE g_HandleEvent;

wchar_t string_data[] = L"Garbage data is absloute thing";

int main(int argc, char* argv[])
{
    g_HandleEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

    auto file_name = L"Cayot.txt";
    auto handle_file = CreateFile(file_name, GENERIC_WRITE, FILE_SHARE_WRITE, 0, CREATE_ALWAYS, FILE_FLAG_OVERLAPPED, 0);

    if (handle_file == INVALID_HANDLE_VALUE)
    {
        std::cout << "File creation is failed." << std::endl;
        return -1;
    }

    OVERLAPPED overlapped_instance = { 0 };
    overlapped_instance.hEvent = g_HandleEvent;

    WriteFileEx(handle_file, string_data, sizeof(string_data), &overlapped_instance, FileIOCompletionRoutine);

    SleepEx(INFINITE, TRUE);

    return 0;
}

Error compiler:

error LNK2001: unresolved external symbol "void __stdcall FileIOCompletionRoutine(unsigned long,unsigned long,struct _OVERLAPPED *)" (?FileIOCompletionRoutine@@YGXKKPAU_OVERLAPPED@@@Z)

Upvotes: 0

Views: 316

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595742

You have merely forward-declared the FileIOCompletionRoutine() function, which satisfies the compiler, but you have not actually implemented the function, so the linker fails to find it.

#include <windows.h>
#include <iostream>

VOID WINAPI FileIOCompletionRoutine(DWORD, DWORD, LPOVERLAPPED);

HANDLE g_HandleEvent;
wchar_t string_data[] = L"Garbage data is absloute thing";

int main(int argc, char* argv[])
{
    g_HandleEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

    auto file_name = L"Cayot.txt";
    auto handle_file = CreateFile(file_name, GENERIC_WRITE, FILE_SHARE_WRITE, 0, CREATE_ALWAYS, FILE_FLAG_OVERLAPPED, 0);

    if (handle_file == INVALID_HANDLE_VALUE)
    {
        std::cout << "File creation is failed." << std::endl;
        return -1;
    }

    OVERLAPPED overlapped_instance = { 0 };
    overlapped_instance.hEvent = g_HandleEvent;

    WriteFileEx(handle_file, string_data, sizeof(string_data), &overlapped_instance, FileIOCompletionRoutine);

    SleepEx(INFINITE, TRUE);

    return 0;
}

VOID WINAPI FileIOCompletionRoutine(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)
{
    // Do something here...
}

Upvotes: 1

Related Questions