Wednesday, October 17, 2007

How to declare out and ref parameters with managed C++

Lately, I've been using managed C++ quite a bit. Managed C++ would not be my choice for a project of any size but it's really convenient when you need to create a managed wrapper for C++ classes that you have in-hand.

The replacement syntax available with Visual Studio 2005 is much improved over Visual Studio 2003 (which was the last time I attempted to use managed C++ and so certainly isn’t news). However, I did struggle a bit trying to figure out how to declare what would be out and ref parameters in C# using managed C++.

Normally, I might use the most excellent Reflector in these cases. I just code up the construct in C#, load the assembly into Reflector and then choose the target language in the dissembler window. Unfortunately, Reflector only support the /clr:oldSyntax managed C++ syntax. Various Google searches proved unhelpful as well.

Finally, I stumbled upon the syntax for the tracking reference. Combine that with the System::Runtime::InteropServices::OutAttribute and it’s easy:

public ref class ExampleClass
void OutParameter([System::Runtime::InteropServices::Out] String^% v);
void ByRefParameter(String^% v);

Simple (and unforgettable) once you know!

No comments: