The compiler is right to barf.  You are trying to manipulate a managed
type from an unmanaged function. Different memory heaps, layouts,etc.
Plus the managed type can move. You need a mechanism to keep the managed
type somewhere so you can access it from unmanaged code and let the CLR
know that you are holding an unmanaged reference to the managed type.
The solution is to use the __value type
Sytem::Runtime::InteropServices::GCHandle which allows you to create a
managed type on the managed heap but to hold the pointer to it as a
__value type. The technique for using is quite simple: we call
GCHandle::Alloc to generate a handle  and then GCHandle::Free to free
it.

This is kind of clumsy though so Microsoft a shortcut template called
gcroot<> to simplify the process.


#include <gcroot.h>
#using <mscorlib.dll>
#include <tchar>

#pragma managed
using namespace System;
using namespace System::Runtime::InteropServices;

__nogc class FooWrapper
{
private:
        gcroot<Foo*>m_pFoo;

public:
        FooWrapper()
        { m_pFoo = new Foo(); }
        ~FooWrapper() {}

#pragma unmanaged
        void ShowSomeFooo(int number)

        {
                m_pFoo->ShowSomeFoo(number);
        }
}

Then


Sam Gentile
Co-Author Wrox Professional Visual C++.NET (ISBN 1861005962 )

[EMAIL PROTECTED]
www.project-inspiration.com/sgentile
http://www.project-inspiration.com/sgentile/DotNet.htm
BLOG: http://radio.weblogs.com/0105852/
http://www.project-inspiration.com/sgentile/ScienceFiction.htm





-----Original Message----
From: The DOTNET list will be retired 7/1/02
[mailto:[EMAIL PROTECTED]] On Behalf Of Axel Heitland
Sent: Monday, June 24, 2002 6:07 PM
To: [EMAIL PROTECTED]
Subject: [DOTNET] Callbacks from unmanaged code to managed code

Dear list,

It's quite easy to call unmanaged functions from MC++ and it's easy to
hold a reference to a managed type from unmanaged code as well.

But how the heck can I call a managed function (i.e. an instance member
function) from unmanaged code?!

A direct call is treated as an error by the compiler - is it really so
hard to support this? And if that doesn't work, what's the workaround?

I know that this has been asked before, but the answers in the archives
aren't satisfying :-(

Any pointers are highly appreciated
        Axel

You can read messages from the DOTNET archive, unsubscribe from DOTNET,
or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

You can read messages from the DOTNET archive, unsubscribe from DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to