Click to See Complete Forum and Search --> : Unmanaged class and unmanaged function
martho
December 21st, 2006, 06:35 AM
Hello!
Could someone explain to me when I could use managed types in unmanaged code?
I have an unmanaged class like:
public class CMyClass
In this class I could use managed types like System::String:
void CMyClass::MyFunc(String ^sText)
{ // Do something with sText
}
But if I define an unmanaged function like:
#pragma unmanaged
void MyUnmanagedFunction(String ^sText)
{ // Do something with sText
}
#pragma managed
the compiler gives an error., because String is a managed type.
So whats the difference?
darwen
December 21st, 2006, 08:04 AM
You can't use managed types in unmanaged code : as soon as you reference a managed type the compiler automatically makes the surrounding method managed.
Whether code is compiled as managed or not is not determined by whether you have a ref class or a class. It is determined by whether the code references managed classes.
Hence your error. You are forcing the compiler to produce unmanaged code and unmanaged code cannot reference managed types.
Darwen.
martho
December 21st, 2006, 08:23 AM
Thanks for your reply!
That means although I use "class CMyClass" instead of "ref class CMyClass" the class will be compiled as managed?
I'm asking this because I used a decompiler to have a look at my .exe. And every "ref class" was there and I could browse through the methods and properties. But for "class CMyClass" I only get the classname and a statement pointing out it's native code:
[StructLayout(LayoutKind.Sequential, Size=0x1c), NativeCppClass, DebugInfoInPDB, CLSCompliant(false), MiscellaneousBits(0x40)]
Altough I use functions like
void CMyClass::MyFunc(String ^sText)
{ String ^sNew = sText + "Something";
......
}
in it without getting an error, the compiler seems to generate native code here. Is the decompiler wrong or what am I missing?
martho
December 21st, 2006, 09:48 AM
I got 2 more things to say:
- The "class MyClass" has to be unmanaged, because it references unmanaged COM-types. If I use "class ref MyClass" I get these errors:
error C4368: cannot define 'm_rCom' as a member of managed 'CMyClass': mixed types are not supported
- But if I put the class in #pragma unmanaged, I got errors as well in the function-definition of void CMyClass::MyFunc(String ^sText) for example:
error C3642: 'void CMyClass:MmyFunc(System::String ^sText)' : cannot call a function with __clrcall calling convention from native code
So the class is neither managed nor unmanaged :confused:
martho
January 2nd, 2007, 10:59 AM
Nobody got an idea about this?
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.