Calling managed functions from unmanaged code

My blog has moved.
You can view this post at the following address:
http://www.osherove.com/blog/2004/3/10/calling-managed-functions-from-unmanaged-code.html
Published Wednesday, March 10, 2004 10:48 PM by RoyOsherove
Filed under:

Comments

Wednesday, March 10, 2004 7:02 PM by Andreas Häber

# re: Calling managed functions from unmanaged code

If you really need to work with functions using a different calling convention then there is a little neat trick you can use: http://groups.google.com/groups?selm=ew6mLkV6BHA.1932%40tkmsftngp03

Happily there will be support for doing this in C# in the next or vNextNext :) Looking forward to that.. it's a little pain to ildasm/perl/ilasm post-build.
Thursday, March 11, 2004 3:39 AM by Yuri Gorobets

# re: Calling managed functions from unmanaged code

God Bless You, dude!!!
Keep the right direction :-)
Saturday, March 27, 2004 11:02 AM by Paul Seabury

# re: Calling managed functions from unmanaged code

Is there any way you can post a small trivial example of the first Q&A post? We are currently having problems with some (strangely not all though) delegate callbacks when we mix managed/unmanaged code. This is how we have been doing it in sorta-psuedo-code.

Say our managed Forms app has a function

private void AddListViewItem(ListViewItem * lvi)
{
...
}

and we declare/create a delegate...

public __delegate void AddDelegate(ListViewItem * lvi);
AddDelegate * myAD;
myAD = new AddDelegate(this,AddListViewItem);

Now we can pass a pointer to this class to our unmanaged classes using the <gcroot> mechanism, and then call the delegate.

Object * [] o = {listViewItem1};
_parent->Invoke(_parent->myAD,o);



This works flawlessly in some cases, calling back in on the correct thread etc., but in other cases we get constant exceptions of the "The Application has requested that the runtime terminate it in an unusual way...". Is there something obviously wrong with this? MSDN suggests this as the only way to insure thread safety (and prevent crashes other weird behavior) with Forms controls.

Thanks,

Paul M. Seabury
Saturday, March 27, 2004 4:27 PM by Roy Osherove

# re: Calling managed functions from unmanaged code

I don't have a valid example to show you. But you should try using CLR spy to see what kind of interop trouble you're getting into.
CLR spy is free:
http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=c7b955c7-231a-406c-9fa5-ad09ef3bb37f