C++/CLI mixing managed/unmanaged

  • Thread starter Thread starter jraul
  • Start date Start date
J

jraul

Hi,

This is probably a noobie question but:

I just created a new C++/CLI project in VS 2005. It created an empty
class:

public ref class Class1
{
// TODO: Add your methods for this class here.

};

I added a method and its implementation. I also added an unmanaged
instance (from a native class library I need to use) as a data member
and the compiler complained:

error C4368: cannot define 'mTest' as a member of managed
'TestProj::Class1': mixed types are not supported

Can I not have unmanaged data members in a managed class? If not, how
am I supposed to interop between managed and unmanaged code?

I took out the "public ref" prefix, and the code compiled.
 
jraul said:
Hi,

This is probably a noobie question but:

I just created a new C++/CLI project in VS 2005. It created an empty
class:

public ref class Class1
{
// TODO: Add your methods for this class here.

};

I added a method and its implementation. I also added an unmanaged
instance (from a native class library I need to use) as a data member
and the compiler complained:

error C4368: cannot define 'mTest' as a member of managed
'TestProj::Class1': mixed types are not supported

Can I not have unmanaged data members in a managed class? If not, how
am I supposed to interop between managed and unmanaged code?

I took out the "public ref" prefix, and the code compiled.

No, unfortunately you cannot have a managed C++/CLI class that contains a
native member. Sorry. The implementation of your managed C++/CLI class
(i.e. when you define its methods) can use native local variables, etc.

-- David
 
jraul said:
Hi,

This is probably a noobie question but:

I just created a new C++/CLI project in VS 2005. It created an empty
class:

public ref class Class1
{
// TODO: Add your methods for this class here.

};

I added a method and its implementation. I also added an unmanaged
instance (from a native class library I need to use) as a data member
and the compiler complained:

error C4368: cannot define 'mTest' as a member of managed
'TestProj::Class1': mixed types are not supported

Can I not have unmanaged data members in a managed class? If not, how
am I supposed to interop between managed and unmanaged code?

You have to instead use a pointer to the unmanaged data, and allocate it
with "new" in your constructor and "delete" in your destructor and
finalizer. That way the unmanaged data is stored on the native heap, where
the garbage collector won't try to move it (having the gc move unmanaged
data around would be a total disaster, because unmanaged code might be using
it).
 
Back
Top