Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

c++ - How to modify content of the original variable which is passed by value?

There is an existing API function which does only allow the plugin(DLL) to receive three parameters and perform some action:

int ProcessMe(int nCommand, unsigned int wParam, long lParam);

Now, from the main program(exe), would like to pass two variables to the plugin, and require plugin to modify their content, and main program will read them again, to perform some task.

My question is, from the above function, can I perform this, without changing the function parameters?

Example:

int ProcessMe(int nCommand, unsigned int wParam, long lParam)
{
  // modify the parameters//
  return 0;
}

int main()
{
  BOOL bSave = TRUE;
  int nOption = 0;
  ProcessMe(0, (unsigned int)(&bSave), (long)(&nOption));
  if(FALSE==bSave)
    printf("bSave is modified!");
  return 1;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Place the variables to modify in a struct and pass the pointer to the sturuct to the plug in:

struct MyStruct
{
    BOOL bSave;
    int nOption;
};

int ProcessMe(int nCommand, unsigned int wParam, long lParam)
{
    ((MyStruct*)lParam)->nOption = ...;
    return 0;
}

Use it like this:

int main()
{
  MyStruct struct;
  struct.bSave = TRUE;
  struct.nOption = 0;
  ProcessMe(0, 0, (long)(&struct));
  if(FALSE==struct.bSave)
    printf("bSave is modified!");
  return 1;
}

Strictly speaking this is undefined behavior. You need to check, whether it works on your platform.

Note: I used a struct here, because this way you can also pass more variables or larger variables such as double to the function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...