c++visual-c++linker-errorsnt-native-api

LNK2019 unresolved external symbol NtOpenFile


I am facing linker error with my code. I am trying to compile with Visual Studio command Prompt (2010) in Win-7 X64 bit m/c. The error which i see are as below.

dust2.obj

dust2.obj : error LNK2019: unresolved external symbol _NtOpenFile@24 referenced in function _main

dust2.obj : error LNK2019: unresolved external symbol _RtlAnsiStringToUnicodeStr ing@12 referenced in function _main

dust2.obj : error LNK2019: unresolved external symbol _RtlInitAnsiString@8 refer enced in function _main

dust2.exe : fatal error LNK1120: 3 unresolved externals

The simplified version of my code is like this:

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

   using namespace std;

   int main()
   {
        NTSTATUS Status;
        OBJECT_ATTRIBUTES Obja;
        HANDLE SourceFile;
        PUNICODE_STRING PathName=0;
        PANSI_STRING p_path=0;
        const char* ccp_path = "D:\\txt.txt";
        RtlInitAnsiString( p_path,ccp_path );
        RtlAnsiStringToUnicodeString( PathName, p_path, true );
        IO_STATUS_BLOCK IoStatusBlock;
        wprintf(L"%s", PathName->Buffer);
        InitializeObjectAttributes(
            &Obja,
            PathName,
            OBJ_CASE_INSENSITIVE,
            NULL,
            NULL
        );
        Status = NtOpenFile(
                     &SourceFile,
                     FILE_LIST_DIRECTORY | FILE_READ_EA | FILE_READ_ATTRIBUTES,
                     &Obja,
                     &IoStatusBlock,
                     FILE_SHARE_READ | FILE_SHARE_WRITE,
                     FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT | FILE_OPEN_REPARSE_POINT
        );  
        if(SourceFile == INVALID_HANDLE_VALUE){
            printf("\nError: Could not open file\n");
            return 0;
        }
        cout<<endl<<endl;
        system("pause");
        return 0;

}

In another post in this forum the solution of these kind of problem was mention to include a #pragma.

I tried this solution by adding #pragma like this

#pragma comment(lib, "ntdll")

but on compilation i see another error that says "LINK : fatal error LNK1104: cannot open file 'ntdll.lib'".

I will much appreciate your help to resolve this problem. Thanks..


Solution

  • These functions cannot be called directly because they belong to internal API and are not exposed through any of the libraries. You need to obtain addresses of these function using GetProcAddress.

    For more information look here.