IN/OUT 参数以及如何在 C++ 中使用它们
从不同类型的外部库中阅读有关函数的文档时,我总是看到文档声明变量必须是 [IN/OUT].有人可以让我详细了解 [IN/OUT] 如何与按引用或按值传递的函数参数相关联.
When reading documentation on functions from external libraries of different kinds I have always seen the documentation state that a variable has to be [IN/OUT]. Could someone give me a detailed understanding on how [IN/OUT] relates to parameters of a function being passed by reference or by value.
这是我遇到的一个函数示例,它告诉我它需要一个 [IN/OUT] 参数:
Here is an example of a function I have come across that tells me it needs an [IN/OUT] parameter:
原型:ULONG GetActivationState( ULONG * pActivationState );
Prototype: ULONG GetActivationState( ULONG * pActivationState );
参数
- 类型: ULONG*
- 变量:pActivationState
- 模式:输入/输出
- Type: ULONG*
- Variable: pActivationState
- Mode: IN/OUT
推荐答案
这个参数输入/输出是因为你提供了一个在函数内部使用的值,并且函数修改它来通知你关于函数内部发生的事情.这个函数的用法是这样的:
This parameter is in/out because you provide a value that is used inside the function, and the function modifies it to inform you about something that happened inside the function. The usage of this function would be something like this:
ULONG activationState = 1; // example value
ULONG result = GetActivationState(&activationState);
请注意,您必须提供变量的地址,以便函数可以在函数外获取值并设置值.例如,GetActivationState
函数可以执行如下操作:
note that you have to supply the address of the variable so that the function can get the value and set the value outside the function. For instance, the GetActivationState
function can perform something like this:
ULONG GetActivationState(ULONG* pActivationState)
{
if (*pActivationState == 1)
{
// do something
// and inform by the modification of the variable, say, resetting it to 0
*pActivationState = 0;
}
// ...
return *pActivationState; // just an example, returns the same value
}
注意方法:
- 该函数接受参数作为指向 UINT 的非常量指针.这意味着它可以修改它.
- 该函数可以通过取消引用来访问您赋予参数的值
- 该函数可以通过取消引用来再次修改参数.
- 调用函数看到
activationState
变量保存了 new 值(在本例中为 0).
- The function accepts the parameter as a non-const pointer to an UINT. This means it may modify it.
- The function can access the value you gave to the parameter by dereferencing it
- The function can modify the parameter again by dereferencing it.
- The calling function sees the
activationState
variable holding the new value (0 in this case).
这是一个通过引用传递"的例子,它是通过在 C 中使用指针来执行的(在 C++ 中也使用引用.)
This is an example of "pass by reference", which is performed by using pointers in C (and also with references in C++.)
相关文章