Why doesn't this code work?

Why doesn't this code work
 Using C++ .NET 2005:

// MSS.cpp : main project file.

#include "stdafx.h"
#include "stdio.h"
#include "iostream"
using namespace System;

int main(array<System::String ^> ^args){
struct tnode {

int count;

System::String ^ word;

} ;

tnode smth;

smth.word="Sometext";

Console::WriteLine( smth.word );
}




Answer this question

Why doesn't this code work?

  • Adam Friedman

    Hi MsFiT, Could you be a bit more specific please
    What error did you get


  • ScottLeo

    Bit is there any equivalent to this code
    struct tnode {
    System::String ^ word;
    } ;



  • hrh

    error C3265: cannot declare a managed 'word' in an unmanaged 'main::tnode'

    may not declare a global or static variable, or a member of a native type that refers to objects in the gc heap



  • cllard

    You have an unmanaged class (a struct is treated as a class) with a managed data member.  C++/CLI does not allow this, nor its converse: a managed class with an unmanaged data member.

    You can do three things:
    1. change to ref struct (making it a value-type), and move it out of the main (since you cannot have local definitions of managed types)
    2. change to ref class, and move it out of main
    3. if you need the struct to be unmanaged, use the gcroot template.  (You can find this in MSDN)

    I suspect 1 is the best solution for you.

    Brian


  • RedHedToo

    As I said, you can use gcroot if you must have an unmanaged struct containing a managed object.

  • Why doesn't this code work?