我试图在函数调用中使用 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/