Ok, I understand the previous section of code, and I have found examples on
the msdn website that shows examples of this exact same code snippet. Here's
yet another problem I am unsure of. I have the following class structure,
and need to pass a reference or pointer of an managed class into an
unmanaged class. The reason is that I have an unmanaged class that would
normally be sub-classed and then passed into yet another unmanaged class and
have it's methods called as callbacks. The solution I have come up with is
to have a managed class with an instance of an unmanged class as it's member
which would simply call it's parent's mirrored methods.
__gc class ExposedManagedClass {
ExposedManagedClass() {
// need to pass managed pointer to self to unmanaged class. does
passing in a reference work?
_myCallbackDeletegate = new UnmanagedCallbackInterface( *this );
}
// programmer overrides this method.
void Foo( ManagedObj mo );
private:
UnmagedClallBackInterface* _myCallbackDeletegate;
private:
__nogc UnmanagedCallbackInterface : CallbackInterface {
public:
UnmanagedCallbackInterface( ExposedManagedClass& emc ) :
_parent(emc) { }
virtual void Foo( UnManagedObj uo ) {
ManagedObj mo = FromUnmangedObjToManagedObj( uo );
_parent.Foo( mo );
private:
ExposedManagedClass& _parent;
};
};
"Ronald Laeremans [MSFT]" <ro*****@online.microsoft.com> wrote in message
news:ue**************@tk2msftngp13.phx.gbl...
No, you don't need to pin this.
You only need pinning when you are going to pass the address of a member
of a __gc type over to unmanaged code I.e. treating it at a __nogc *).
Marshal::StringToHGLobalAnsi directly returns a __nogc *. It does this by
allocating memory from the NT heap and translating/copyign the string data
into that buffer.
Ronald Laeremans
Visual C++ team
"Jacob Gladish" <ja**********@yahoo.com> wrote in message
news:OQ**************@TK2MSFTNGP10.phx.gbl... In the following code snippet, I am calling into an unmanaged static
..lib file from a managed class. I belive that I have to pin the pointer
before making the call into the unmanaged code, but I don't completely
understand when a pin is required. Any thoughts?
void p4dn::ClientUser::OutputError( System::String* errString )
{
System::IntPtr ptr = Marshal::StringToHGlobalAnsi( errString );
// does this need to be pinned?
char __pin* str = static_cast< char * >( ptr.ToPointer() );
// unmanged code from static .lib
_clientUser->OutputError( str );
Marshal::FreeHGlobal( ptr );
}