473,785 Members | 2,789 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Garbage Collector and Delegate

I am registering a managed delegate to an unmanaged DLL for asynchronous
callback. I understand the garbage collector will free the managed resource
if they go out of scope but with the information I have read, it is unclear
to me if the garbage collector will move the delegate (e.g.
cableInterruptC allbackEventHan dler) if it is still referenced thereby
invalidating the callback performed by the unmanaged code. I would greatly
appreciate some information regarding this topic. I have included some code
that will illustrate what I am doing. In my actual code I am implementing
the Dispose Pattern. Sorry, it is a bit lengthy.

[btapi.h] (partial)
#ifdef __cplusplus
#define BT_EXTERN extern "C"
#else
#define BT_EXTERN extern
#endif

#if !defined(BT973) && !defined(WINVER ) && !defined(BT1590 1) \
&& !defined(BT1599 1) && !defined(BT1790 3) && !defined(BT1390 8)
#define BT_METHOD
#else
/* Windows requires __stdcall between the return type and the function
name- so we can't just hide it in BT_EXTERN. */
#define BT_METHOD __stdcall
#endif

BT_EXTERN bt_error_t
BT_METHOD bt_icbr_install (
bt_desc_t btd_p,
bt_irq_t irq_type,
bt_icbr_t *icbr_p,
void *param_p,
bt_data32_t vector);

BT_EXTERN bt_error_t
BT_METHOD bt_icbr_remove(
bt_desc_t btd_p,
bt_irq_t irq_type,
bt_icbr_t *icbr_p);
[C#]
using System;
using System.Runtime. InteropServices ;

namespace SbsTechnologies .BusAdapter
{
public enum ErrorStatus : int
{
Success,
IOError,
DeviceDoesNotEx ist,
OutOfMemory,
}

public enum InterruptType : int
{
Overflow,
Error,
Programmed,
Cable,
}

public enum InterruptCallba ckType : int
{
Error = InterruptType.E rror,
Programmed = InterruptType.P rogrammed,
Cable = InterruptType.C able,
}

public class MirrorApiEventA rgs : EventArgs
{
private InterruptType interruptType;
private uint vector;

public MirrorApiEventA rgs(InterruptTy pe interruptType, uint vector) : base()
{
this.interruptT ype = interruptType;
this.vector = vector;
}

public InterruptType InterruptType
{
get
{
return this.interruptT ype;
}
}

public uint Vector
{
get
{
return this.vector;
}
}
}

internal delegate void InterruptCallba ckEventHandler( IntPtr parameter,
InterruptType interruptType, uint vector);

public delegate void MirrorApiEventH andler(object sender,
MirrorApiEventA rgs e);

internal sealed class MirrorApiIntero p
{
private sealed class UnsafeNativeMet hods
{

[DllImport(@"bit 3_984.dll", EntryPoint = "bt_icbr_instal l")]
public static extern ErrorStatus bt_icbr_install (
IntPtr btd_p,
InterruptCallba ckType irq_type,
InterruptCallba ckEventHandler icbr_p,
IntPtr param_p,
uint vector
);

[DllImport(@"bit 3_984.dll", EntryPoint = "bt_icbr_remove ")]
public static extern ErrorStatus bt_icbr_remove(
IntPtr btd_p,
InterruptCallba ckType irq_type,
InterruptCallba ckEventHandler icbr_p
);
}

internal static void InstallInterrup tCallbackRoutin e(IntPtr handle,
InterruptCallba ckType interruptCallba ckType, InterruptCallba ckEventHandler
interruptCallba ckEventHandler, IntPtr param, uint vector)
{
UnsafeNativeMet hods.bt_icbr_in stall(handle, interruptCallba ckType,
interruptCallba ckEventHandler, param, vector);
}

internal static void RemoveInterrupt CallbackRoutine (IntPtr handle,
InterruptCallba ckType interruptCallba ckType, InterruptCallba ckEventHandler
interruptCallba ckEventHandler)
{
UnsafeNativeMet hods.bt_icbr_re move(handle, interruptCallba ckType,
interruptCallba ckEventHandler) ;
}
}

public class MirrorApiInterr upt
{
private IntPtr handle;
private uint vector;

private InterruptCallba ckEventHandler cableInterruptC allbackEventHan dler;
private InterruptCallba ckEventHandler errorInterruptC allbackEventHan dler;
private InterruptCallba ckEventHandler
programmedInter ruptCallbackEve ntHandler;

public event MirrorApiEventH andler Cable;
public event MirrorApiEventH andler Error;
public event MirrorApiEventH andler Programmed;

public MirrorApiInterr upt(IntPtr handle, uint vector)
{
this.handle = handle;
this.vector = vector;

cableInterruptC allbackEventHan dler = new
InterruptCallba ckEventHandler( this.CableInter ruptCallback);
errorInterruptC allbackEventHan dler = new
InterruptCallba ckEventHandler( this.ErrorInter ruptCallback);
programmedInter ruptCallbackEve ntHandler = new
InterruptCallba ckEventHandler( this.Programmed InterruptCallba ck);

MirrorApiIntero p.InstallInterr uptCallbackRout ine(this.handle ,
InterruptCallba ckType.Cable, cableInterruptC allbackEventHan dler, IntPtr.Zero,
this.vector);
MirrorApiIntero p.InstallInterr uptCallbackRout ine(this.handle ,
InterruptCallba ckType.Error, errorInterruptC allbackEventHan dler, IntPtr.Zero,
this.vector);
MirrorApiIntero p.InstallInterr uptCallbackRout ine(this.handle ,
InterruptCallba ckType.Programm ed, programmedInter ruptCallbackEve ntHandler,
IntPtr.Zero, this.vector);
}

~MirrorApiInter rupt()
{
MirrorApiIntero p.RemoveInterru ptCallbackRouti ne(this.handle,
InterruptCallba ckType.Cable, cableInterruptC allbackEventHan dler);
}

private void CableInterruptC allback(IntPtr parameter, InterruptType
interruptType, uint vector)
{
this.OnCable(ne w MirrorApiEventA rgs(interruptTy pe, vector));
}

private void ErrorInterruptC allback(IntPtr parameter, InterruptType
interruptType, uint vector)
{
this.OnError(ne w MirrorApiEventA rgs(interruptTy pe, vector));
}

private void ProgrammedInter ruptCallback(In tPtr parameter, InterruptType
interruptType, uint vector)
{
this.OnProgramm ed(new MirrorApiEventA rgs(interruptTy pe, vector));
}

protected virtual void OnCable(MirrorA piEventArgs e)
{
if (this.Cable != null)
{
this.Cable(this , e);
}
}

protected virtual void OnError(MirrorA piEventArgs e)
{
if (this.Error != null)
{
this.Error(this , e);
}
}

protected virtual void OnProgrammed(Mi rrorApiEventArg s e)
{
if (this.Programme d != null)
{
this.Programmed (this, e);
}
}
}
}

Nov 16 '05 #1
2 2361
Daniel,
I understand the garbage collector will free the managed resource
if they go out of scope but with the information I have read, it is unclear
to me if the garbage collector will move the delegate (e.g.
cableInterrupt CallbackEventHa ndler) if it is still referenced thereby
invalidating the callback performed by the unmanaged code. I would greatly
appreciate some information regarding this topic.
The delegate may move, but the native function pointer that gets
passed to the function you're calling will remain valid as long as the
delegate is referenced.

In my actual code I am implementing the Dispose Pattern.


Great, because when your ~MirrorApiInter rupt finalizer runs the
delegate may already have been garbage collected, so you can't safely
call RemoveInterrupt CallbackRoutine from there.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #2
Thanks for the help. Your time is appreciated.

"Mattias Sjögren" wrote:
Daniel,
I understand the garbage collector will free the managed resource
if they go out of scope but with the information I have read, it is unclear
to me if the garbage collector will move the delegate (e.g.
cableInterrupt CallbackEventHa ndler) if it is still referenced thereby
invalidating the callback performed by the unmanaged code. I would greatly
appreciate some information regarding this topic.


The delegate may move, but the native function pointer that gets
passed to the function you're calling will remain valid as long as the
delegate is referenced.

In my actual code I am implementing the Dispose Pattern.


Great, because when your ~MirrorApiInter rupt finalizer runs the
delegate may already have been garbage collected, so you can't safely
call RemoveInterrupt CallbackRoutine from there.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.

Nov 16 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2053
by: pachanga | last post by:
The Hans-Boehm garbage collector can be successfully used with C and C++, but not yet a standard for C++.. Is there talks about Garbage Collector to become in the C++ standard?
11
3676
by: Fabien Penso | last post by:
Hi. I am trying to make this work but I got a weird behavior. I got a very basic system, I call a unmanaged "dllimported" function and give it a structure of callback functions. Sometimes, the unmanaged part calls one of the callback functions. But the first one has its pointer changed from its address to "0x00000001". I can't figure out why.
9
2193
by: Olivier Fermy | last post by:
I have created a sample project where i have referenced an object only with an event : textBox.VisibleChanged += new EventHandler(this.textBox_VisibleChanged); When i call GC.Collect(), the object is disposed and garbage collected ! I thought that event references are strong references and not weak references. Does the .NET 2.0 garbage collector manage differently the events references ?
14
2942
by: Christian Kaiser | last post by:
We have a component that has no window. Well, no window in managed code - it uses a DLL which itself uses a window, and this is our problem! When the garbage collector runs and removes our component (created dynamically by, say, a button click, and then not referenced any more), the GC runs in a different thread, which prohibits the DLL to destroy its window, resulting in a GPF when the WndProc of that window is called - the code is gone...
4
1699
by: R. MacDonald | last post by:
Hello, all, I have a .NET application (VB) that passes the address of a delegate to unmanaged code in a DLL. The unmanaged code then uses the delegate as a call-back. This seems to work fine, but now I am worried about garbage collection. I am concerned that the location of the delegate might be altered as a result of other (unused) objects being garbage collected. This would probably cause undesirable results when the unmanaged DLL...
28
3188
by: Goalie_Ca | last post by:
I have been reading (or at least googling) about the potential addition of optional garbage collection to C++0x. There are numerous myths and whatnot with very little detailed information. Will this work be library based or language based and will it be based on that of managed C++? Then of course there are the finer technical questions raised (especially due to pointer abuse). Is a GC for C++ just a pipe dream or is there a lot of work...
13
14563
by: Wilfried Mestdagh | last post by:
Hi, I have an application using a DLL and callbacks. It generate random the error "A callback was made on a garbage collected delegate". I found some articles that the pointer to the delegate has to have a lifetime reference so that it is not garbage collected. But I could not find any example how to do this. Can someone help here ?
11
1274
by: DoB | last post by:
Hi, Suppose a situation where some object goes out of scope and its reference is not kept anywhere, but a reference to some delegate (that references one of the object's methods) is kept as a value in some map. Is there a possibility that the object is disposed and the delegate will be invalid? Yours DoB
11
2231
by: Jay Dee | last post by:
Object garbage collection of events I can not help wondering how the garbage collection system handles events. If I release all references to an object that has a void that an event somewhere is using I then have no access to the class holding the void so it should be garbage collected. But if an event holds a reference to a void of the class that I have
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10155
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9953
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8978
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7502
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6741
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5383
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3655
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.