c++ - 函数调用中的 WriteConsole 访问冲突但不是来自 main()

标签 c++ windows function winapi

我试图在函数调用中使用 WriteConsole(..),但我遇到了访问冲突。当我在 main 中取消注释代码时,它会在 main 函数中毫无问题地将我的文本打印到屏幕上。当我尝试在函数调用中打印字符串时,我遇到了访问冲突,即使它确实将文本打印到控制台。

void print(char *_charArray);

int _tmain(int argc, _TCHAR* argv[])
{

    HWND hConsole;
//    HANDLE hFile;
    char myText[] = "This is my text";
    char *pMyText = myText;
    LPDWORD charsWriten;


//    hFile = CreateFile("CONOUT$", GENERIC_WRITE, FILE_SHARE_READ, NULL,
//        OPEN_EXISTING, 0, NULL);

    print(pMyText);

//    WriteConsole(hFile, myText, sizeof(myText), charsWriten, NULL);


    getch();
    return 0;
}

void print(char *text)
{
    LPDWORD charsWriten;
    HANDLE hFile;

    hFile = CreateFile("CONOUT$", GENERIC_READ | GENERIC_WRITE,
                    FILE_SHARE_WRITE | FILE_SHARE_READ, NULL,
                    OPEN_EXISTING, 0, NULL);

    unsigned int strn = strlen(text) + 1;

    if(!WriteConsole(hFile, text, (strlen(text) + 1), charsWriten,NULL))
    {
        printf("Write Failed\n");
    }
}

最佳答案

这个声明是错误的:

LPDWORD charsWriten;

CreateFile 函数期望第四个参数是指向它可以写入的变量的指针。但是,您实际上并没有分配内存;您只需声明一个指针——一个未初始化的指针。那行不通的。你需要做的:

DWORD charsWritten;

...

WriteConsole(hFile, text, (strlen(text) + 1), &charsWritten, NULL)

这将解决访问冲突问题,但它不能解释为什么要在字符串末尾后写入一个字符。 strlen 不需要加 1;不需要写入终止 NUL。

关于c++ - 函数调用中的 WriteConsole 访问冲突但不是来自 main(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43833314/

相关文章:

python - 打印当前模块名称的函数,当从另一个模块调用时也是如此

c++ - 将 XSD 文件嵌入一个(二进制)文件中

c# - 如何在 TreeView 中获取当前选定的节点

c++ - 套接字动态绑定(bind)到缩小范围

windows - 对 IID_ImageList 的 undefined reference

c# - 调试混合模式应用程序(c# 和非托管 c++)时出现 "The breakpoint will not currently be hit"错误

c - 如何在 C 中的两个函数之间共享一个变量?

JavaScript 删除动态创建的 tr

c++ - 在 DateEdit Qt C++ 中打开 .txt 中的日期

c++ - 移植我的 C++ 应用程序以在浏览器中运行