Groups | Blog | Home
all groups > dotnet clr > october 2006 >

dotnet clr : Calling Managed functions from unmanaged class


Amit Dedhia
10/11/2006 4:16:35 PM
Hi All

I have a VC++ 2005 MFC application with all classes defined as
unmanaged classes. I want to write my application data in xml format.
Since ADO.NET has buit in functions available for this, I want to use
it. Is it possible to call Managed class functions from Unmanaged
class? How to do it?

I did something like this.
I declared a managed class (in C++ CLI) called as MyManagedClass whose
public interface has functions to write application data in XML format.
It internally uses ADO.NET classes to achieve this. This class is
declared in a seperate dll compiled with '\clr' option.

Now I created an unmanaged wrapper class which wraps the managed class
(defined in the same dll as that of managed class). The unmanaged
wrapper, call it as MyUnmanagedWrapper, has a data member declared as

gcroot<Object^> handleToManagedClass;

This is declared in the top of the class. It has wrapper methods whose
implementation is something like this:

void MyUnmanagedWrapper::Method1()
{
(*this)->Method1();
}

and then I have...

class MyApplicationClass
{
MyUnmanagedWrapperInstance.Method1();
}

Everything complies well. However, when the above method is run, I get
Access Violation error. It does not even go inside the method.

Can anyone tell why there is access violation?

Best regards
Amit Dedhia
Noah Roberts
10/11/2006 4:20:40 PM
Your question is off topic in comp.lang.c++
Amit Dedhia
10/11/2006 6:02:14 PM

[quoted text, click to view]

Ok Ben...I got the point

Regarding initialization of the object, I would have a static method in
MyManagedClass which returns an instance of iteself. I will call this
method in ctor of the MyUnmanagedWrapper. However, I still have one
question. I have both these classes defined in the same managed dll
(compiled with /clr option). How do I use this dll (and its classes)
from say an MFC dialog based application client?


[quoted text, click to view]
Ben Voigt
10/11/2006 6:31:07 PM

[quoted text, click to view]

Should be
gcroot<MyManagedClass^> handleToManagedClass;

[quoted text, click to view]
Should be
handleToManagedClass->Method1();

[quoted text, click to view]
Where is handleToManagedClass initialized? Initially it will hold a
nullptr. Testing a gcroot for nullptr is a pain, try:
(handleToManagedClass.operator->() != nullptr)



[quoted text, click to view]

Duane Hebert
10/11/2006 8:05:28 PM

[quoted text, click to view]
I mostly prefer to call "unmanaged" native.
Unless, of course, you prefer to not manage your
code unless MS does it for you. <g>

Alex Blekhman
10/12/2006 12:00:00 AM
[quoted text, click to view]

Is XML writing the only reason for using ADO.NET? If yes,
then it seems like tremendous overkill. It's sufficient to
#import <msxml4.dll> and use perfectly native C++ classes to
AddThis Social Bookmark Button