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
298 views
in Technique[技术] by (71.8m points)

.net - In C++/CLI, how do I declare and call a function with an 'out' parameter?

I have a function which parses one string into two strings. In C# I would declare it like this:

void ParseQuery(string toParse, out string search, out string sort)
{
    ...
}

and I'd call it like this:

string searchOutput, sortOutput;
ParseQuery(userInput, out searchOutput, out sortOutput);

The current project has to be done in C++/CLI. I've tried

using System::Runtime::InteropServices;

...

void ParseQuery(String ^ toParse, [Out] String^ search, [Out] String^ sort)
{
    ...
}

but if I call it like this:

String ^ searchOutput, ^ sortOutput;
ParseQuery(userInput, [Out] searchOutput, [Out] sortOutput);

I get a compiler error, and if I call it like this:

String ^ searchOutput, ^ sortOutput;
ParseQuery(userInput, searchOutput, sortOutput);

then I get an error at runtime. How should I declare and call my function?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

C++/CLI itself doesn't support a real 'out' argument, but you can mark a reference as an out argument to make other languages see it as a real out argument.

You can do this for reference types as:

void ReturnString([Out] String^% value)
{
   value = "Returned via out parameter";
}

// Called as
String^ result;
ReturnString(result);

And for value types as:

void ReturnInt([Out] int% value)
{
   value = 32;
}

// Called as
int result;
ReturnInt(result);

The % makes it a 'ref' parameter and the OutAttribute marks that it is only used for output values.


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

...