[Mono-list] calling a delegate from unmanaged code to managed code
GaoXianchao
gxcmaillist at gmail.com
Mon Apr 10 01:11:55 EDT 2006
hi all,
I want to call a delegate from unmanaged code to managed code.
For some reson, I can't pass the delegate to unmanaged code every
time.So, I remember the delegate in the unmanaged code.
But, the garbage collector will move the delegate object in memory,
how can i avoid this?
thanks a lot!
my code like this:
-------------------------------------------------------
test.h:
typedef void(*callback)(int a, int b);
void set_callback(callback ck);
void update(int a, int b);
-------------------------------------------------------
test.c:
callback g_callback = 0;
void set_callback(callback ck)
{
g_callback = ck;
}
void update(int a, int b)
{
if(g_callback != 0)
{
g_callback(a, b);
}
do_other(a, b);
}
------------------------------------------------------
test.cs
class Program
{
public delegate void callback(int a, int b);
[DllImport("test")]
public static extern void set_callback(callback ck);
[DllImport("test")]
public static extern void update(int a, int b);
static void Main(string[] args)
{
callback ck = new callback(OnCallback);
set_callback(ck);
//long time run...
while(!_toExit)
{
update(1,2);
}
}
static void OnCallback(int a, int b)
{
Console.WriteLine("a:" + a.ToString() + " b:" + b.ToString());
}
}
More information about the Mono-list
mailing list