Value types vs unmanaged pointers in C++/CLI

  • Thread starter Thread starter Ioannis Vranos
  • Start date Start date
I

Ioannis Vranos

This compiles:



value class SomeClass
{};


int main()
{
SomeClass obj;

SomeClass *p= &obj;
}


C:\c>cl /clr temp.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 14.00.41013
for Microsoft (R) .NET Framework version 2.00.41013.0
Copyright (C) Microsoft Corporation. All rights reserved.

temp.cpp
Microsoft (R) Incremental Linker Version 8.00.41013
Copyright (C) Microsoft Corporation. All rights reserved.

/out:temp.exe
temp.obj

C:\c>



Also this compiles:


value class SomeClass
{};


int main()
{
SomeClass obj;

pin_ptr<SomeClass> p= &obj;
}


C:\c>cl /clr temp.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 14.00.41013
for Microsoft (R) .NET Framework version 2.00.41013.0
Copyright (C) Microsoft Corporation. All rights reserved.

temp.cpp
Microsoft (R) Incremental Linker Version 8.00.41013
Copyright (C) Microsoft Corporation. All rights reserved.

/out:temp.exe
temp.obj

C:\c>



Can we get a regular pointer to a value object? Value types can not be
moved from the CLR?
 
Ioannis,
This compiles:



value class SomeClass
{};


int main()
{
SomeClass obj;

SomeClass *p= &obj;
}

Can we get a regular pointer to a value object? Value types can not be
moved from the CLR?

This first case compiles because obj is on the local stack, and obviously
the stack won't be moved itself. Mind you, this is not verifiable, btw.

Had you tried this, however, you'd get an error:

ref struct Cont
{
SomeClass sc_;
};

int main()
{
Cont^ c = gcnew Cont;

SomeClass *p= &c->sc_;
}

t.cpp
t.cpp(17) : error C2440: 'initializing' : cannot convert from
'cli::interior_ptr
<Type>' to 'SomeClass *'
with
[
Type=SomeClass
]
Cannot convert a managed type to an unmanaged type

That said, I did not see anything in the C++/CLI that very obviously
expresses these restrictions; pretty much all coverage of pointers and
interior pointers talks only about "objects in the GC heap", but not about
values on the stack.
 
Back
Top