CLI/C++ Managed pointer to value type (e.g. Int32)?

  • Thread starter Thread starter Mark Ingram
  • Start date Start date
M

Mark Ingram

Hi, I have a function:

void MyFunction(Int32^ outVar)
{
if (outVar != nullptr)
{
*outVar = 32;
}
}

and code:

{
Int32 emptyVar;
MyClass->MyFunction(emptyVar);
}


a) Why does this compile, when I am not actually passing the address of
the variable through to the function?
b) Is that the correct way of doing it? I tried:

MyClass->MyFunction(&emptyVar);

But it moans about converting it from Int32* to Int32^.

Any tips welcome,

Cheers,
 
David said:
For value types, use the "%" symbol for ref parameters:
void MyFunction(Int32% outVar)

I don't know why your original sample compiles though.

I want the parameter to be optional, i.e. the developer can pass nullptr
through as one of the parameters (in my function i have 2 parameters)

void MyFunction(Int32^ param1, Int32^ param2)
{
if (param1 != nullptr)
....

if (param2 != nullptr)
....

}
 
Mark said:
I want the parameter to be optional, i.e. the developer can pass nullptr
through as one of the parameters (in my function i have 2 parameters)

void MyFunction(Int32^ param1, Int32^ param2)
{
if (param1 != nullptr)

You can not do that. Int32 is a value type, and you can't get a
reference handle to a value type. You can only do a tracking reference,
Int32%.

The problem with your function is that when you take the address of an
integer, the compiler creates a temporary object and passes that to
MyFunction. Pseudo code:

ref struct Int32Wrapper
{
int value;
};

int value;
Int32Wrapper^ value_wrapper = gcnew Int32Wrapper;
value_wrapper->value = value;
MyFunction(value_wrapper);

As you see, when you pass your integer to MyFunction, the compiler
creates a copy of your integer, and MyFunction modifies that copy, while
your original integer gets unchanged.

You have to use Int32% or int%.

Tom
 
Tamas said:
As you see, when you pass your integer to MyFunction, the compiler
creates a copy of your integer, and MyFunction modifies that copy, while
your original integer gets unchanged.

You have to use Int32% or int%.

Tom


Hi, thanks for the input, can I not change my function to:

MyFunction(interior_ptr<Int32> param1, interior_ptr<Int32> param2)
{
if (param1 != nullptr)
{
}

if (param2 != nullptr)
{
}
}

....

MyFunction(&int1, &int2);

?

Thanks,
 
Hi, thanks for the input, can I not change my function to:
MyFunction(interior_ptr<Int32> param1, interior_ptr<Int32> param2)
{
if (param1 != nullptr)
{
}

if (param2 != nullptr)
{
}
}

In the C++/CLI standard, I have not found a statement regarding a standard
conversion from int* to interior_ptr<int>,
however, Visual C++ 2005 implements this conversion. Therefore, yes, you can
do this in VC++ 2005.

If you want to be interoperable with other .NET languages, you should not
use interior_ptr, but Nullable<int> instead.

Marcus
 
Back
Top