Value types vs unmanaged pointers in C++/CLI

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?
 
T

Tomas Restrepo \(MVP\)

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top