Max Pollack
Max Pollack

Reputation:

Passing a ref or pointer to a managed type as an argument in C++.net

I'm really baffled by this - I know how to do this in VB, unmanaged C++ and C# but for some reason I can't accept a ref variable of a managed type in C++. I'm sure there's a simple answer, really - but here's the C# equivalent:

myClass.myFunction(ref variableChangedByfunction);

I've tried C++ pointers - no dice. I've tried ref keywords. No dice. I tried the [out] keyword. Didn't work.

I can't find any documentation that clearly explains my problem, either.

Upvotes: 0

Views: 2678

Answers (3)

rotti2
rotti2

Reputation: 251

Just to make it a little clearer:

Parameters of reference types (e.g. System::String) have to be denoted with ^ in the newer C++/CLI syntax. This tells the compiler that the parameter is a handle to a GC object.

If you need a tracking reference (like with ref or out in C#) you need to add % as well.

And here comes a tip: I often find it helpful to use the .NET Reflector to look at existing assemblies and switch to C++ code style. This gives good insight into usage of attributes for interoperability between different .net languages.

Upvotes: 1

Max Pollack
Max Pollack

Reputation:

Turns out in the function declaration you need to use a % after the parameter name:

bool Importer::GetBodyChunk(String^% BodyText, String^% ChunkText)

And then you pass in the variable per usual.

Upvotes: 5

Joel Coehoorn
Joel Coehoorn

Reputation: 415690

Use a ^ instead of a *

Upvotes: 2

Related Questions