C++/CLI Unions and Garbage collection

M

minorguy

1.) In C++/CLI, I have the following structures defined, which work as
unions:


[StructLayout(LayoutKind::Explicit)]
public ref struct One
{
[FieldOffset(0)] Int32 a;
};

[StructLayout(LayoutKind::Explicit)]
public ref struct Two
{
[FieldOffset(0)] Int32 a;
};

[StructLayout(LayoutKind::Explicit)]
public ref struct MyUnion
{
[FieldOffset(0)] One^ one;
[FieldOffset(0)] Two^ two;
};


Then I use these structures from C# and write the following:

MyUnion mu = new MyUnion();
mu.one = new One();
mu.two = new Two(); // is the instance of class One now available for
GC?
mu.two.a = 42;

Has the memory allocated for One now been made available for garbage
collection?
Obviousy it would in the typical case when One^ and Two^ don't overlap. But
what if they do? Does the garbage collector still track this?

------------------------------------

2.) For my second question: is it known what the size of a reference
handle is?
For example, if I were to instead write MyUnion as:

[StructLayout(LayoutKind::Explicit)]
public ref struct MyUnion
{
[FieldOffset(0)] One^ one;
[FieldOffset(4)] Two^ two; // <--- note different field offset
};

Am I allowed to depend on One^ taking up four bytes?


Thanks!
 
C

Carl Daniel [VC++ MVP]

minorguy said:
Then I use these structures from C# and write the following:

MyUnion mu = new MyUnion();
mu.one = new One();
mu.two = new Two(); // is the instance of class One now available
for GC?
mu.two.a = 42;

Has the memory allocated for One now been made available for garbage
collection?
Yes.

Obviousy it would in the typical case when One^ and Two^ don't
overlap. But what if they do? Does the garbage collector still track
this?
------------------------------------

2.) For my second question: is it known what the size of a reference
handle is?
For example, if I were to instead write MyUnion as:

[StructLayout(LayoutKind::Explicit)]
public ref struct MyUnion
{
[FieldOffset(0)] One^ one;
[FieldOffset(4)] Two^ two; // <--- note different field
offset };

Am I allowed to depend on One^ taking up four bytes?

No. The size of a reference is (I believe) undefined. It's certainly not 4
bytes on a 64-bit CLR.

-cd
 
M

minorguy

Thanks for your response.

Carl Daniel said:
No. The size of a reference is (I believe) undefined. It's certainly not
4 bytes on a 64-bit CLR.

Yeah, I figured it would be different on 64-bit. What I was looking for was
whether it was defined at all, like C++ pointers are. Thanks.
 

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

Similar Threads


Top