Re: using yacc union in managed c++

George Neuner <>
13 Apr 2007 01:35:58 -0400

          From comp.compilers

Related articles
using yacc union in managed c++ (ras) (2007-04-11)
Re: using yacc union in managed c++ (Chris Dodd) (2007-04-13)
Re: using yacc union in managed c++ (George Neuner) (2007-04-13)
| List of all articles for this month |

From: George Neuner <>
Newsgroups: comp.compilers
Date: 13 Apr 2007 01:35:58 -0400
Organization: Compilers Central
References: 07-04-032
Keywords: yacc, C++
Posted-Date: 13 Apr 2007 01:35:58 EDT

On 11 Apr 2007 23:34:10 -0400, "ras" <> wrote:

>Is there a way to implement the union in a managed c++ yacc parser?

This is a solution from MSDN magazine:

The common language runtime (CLR) doesn't understand unions, but you
can use an ordinary __value struct with some special voodoo to tell it
where your members go. The magic attributes are StructLayout and
FieldOffset. In managed C++, it looks like this:

public __value struct MyUnion {
    [FieldOffset(0)] int i;
    [FieldOffset(0)] double d;

This tells the CLR that the integer i and the double d are both at
offset zero (that is, the first items) in your struct, which makes
them overlap and, in effect, the struct is a union. You can then use
MyUnion in your __gc class, like so:

public __gc class CUnionClass {
    // can access this directly because it's public
    MyUnion uval;

With CUnionClass defined, you can access the members i and d directly
through uval from any .NET-compliant language. In C# it looks like the
following code snippet:

CUnionClass obj = new CUnionClass();
obj.uval.i = 17;
obj.uval.d = 3.14159

See for more.

Hope this helps.

Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.