Click to See Complete Forum and Search --> : Making an instance of a managed class in unmanaged code


Lars_V_J
October 29th, 2009, 10:41 AM
if I have (managed c++)

namespace MyNS
{
class MyManagedClass
{
....
};
}

and then in my UNmanaged code:

class MyUnmanagedClass
{
void MyFunc();
}

void MyUnmanagedClass::MyFunc()
{
MyNS::MyManagedClass *p = new MyNS::MyManagedClass();
}

I get

error C3150: 'p' : '__gc' can only be applied to a class, struct, interface, array or pointer
error C3821: 'MyNS::MyManagedClass': managed type cannot be used in an unmanaged function

Is there a way around that? The only one I've seen is to declare the managed class static, and then use functions to call the static member functions. This is not good, as it only allows one instance of the class.

Thanks in advance.

cilu
October 29th, 2009, 11:11 AM
You're using VS 2003? In 2005 and 2008 you can use gcroot<> to do that. With 2003 I'm not very familiar.

Lars_V_J
October 29th, 2009, 11:37 AM
I use VC 2003. I looked it up, and it was there, thanks.

I then tried to add to one of my functions

MyUnmanagedClass::MyFunction()
{
gcroot<MyNS::MyManagedClass*> p = new MyNS::MyManagedClass();
}

I still got the same error.

In the msdn example they use a system::string, but I need to use my own class
Any ideas?

cilu
October 29th, 2009, 11:55 AM
I think it should be like this:

MyUnmanagedClass::MyFunction()
{
gcroot<MyNS::MyManagedClass __gc*> p = new MyNS::MyManagedClass();
}

Lars_V_J
October 30th, 2009, 04:56 AM
Hm, I still get the same error.

The sample code MS provided is this


// mcpp_nested_classes7.cpp
// compile with: /clr
#using <mscorlib.dll>
#include <vcclr.h>
using namespace System;

class CppClass {
public:
gcroot<String*> str; // can use str as if it were String*
CppClass() {}
};

int main() {
CppClass c;
c.str = new String("hello");
Console::WriteLine( c.str ); // no cast required
}


I then tried to add the declaration as a class variable to my unmanaged class. That was okay. But when I then wanted to initialize it in my function, then it nagged me with the same error again.

cilu
October 30th, 2009, 05:39 AM
[ redirected ]

I don't know. And I don't have VS 2003 to try it out.

Lars_V_J
October 30th, 2009, 05:54 AM
Thanks anyway for trying :-)

Alex F
October 30th, 2009, 07:04 AM
Your managed class is not managed. In managed C++ it should be declared with __gc keyword, in C++/CLI - with ref keyword.
gcroot is used to keep managed class instance as member of unmanaged class. To create local instance of managed class, gcroot is not necessary.
Managed class instance may be created in any C++ code compiled with /clr switch.