问题描述
在我的程序中,我有以下代码:
In my program I've the following code:
//Code
if not CreateProcess(nil, NonConstCmd, nil, nil, True, NORMAL_PRIORITY_CLASS or
CREATE_NEW_PROCESS_GROUP, nil, PCh, SI, P) then
//Code
而且我不断收到访问冲突错误.顺便说一句,在 Delphi7 中,相同的代码可以完美运行.我读过MSDN,发现Delphi中的CreateProcess函数可以修改第二个参数.最初它是 const,这就是为什么我创建一个具有相同值的新变量.但是没有效果.
And I keep getting Access violation error.By the way, in Delphi7 the same code works perfectly.I've read MSDN and found that CreateProcess function in Delphi can modify the second argument.Inititally It was const, that's why I create a new variable with the same value.But it takes no effect.
问题是:为什么这段代码不起作用?
The question is: why doesn't this code work?
推荐答案
问题出在 lpCommandLine
参数中.我怀疑你正在做这样的事情:
The problem is in the lpCommandLine
parameter. I suspect you are doing something like this:
var
CmdLine: string;
...
CmdLine := 'notepad.exe';
CreateProcess(nil, PChar(CmdLine), ...)
这会导致访问冲突,因为 CmdLine
不是可写内存.该字符串是存储在只读存储器中的常量字符串.
This results in an access violation because CmdLine
is not writeable memory. The string is a constant string stored in read-only memory.
相反,您可以这样做:
CmdLine := 'notepad.exe';
UniqueString(CmdLine);
CreateProcess(nil, PChar(CmdLine), ...)
这足以让 CmdLine
由可写内存支持.
This is enough to make CmdLine
be backed by writeable memory.
仅仅使保存字符串的变量非常量是不够的,您还需要使支持字符串的内存也可写.将字符串字面量分配给字符串变量时,字符串变量指向只读内存.
It is not enough just to make the variable holding the string non-const, you need to make the memory that backs the string writeable too. When you assign a string literal to a string variable, the string variable points at read-only memory.
这篇关于Delphi 2009 中函数 CreateProcess 中的访问冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!