Tom Davies
Tom Davies

Reputation: 2446

Cache to map IntPtr handles to C# class instances in pinvoke callbacks

I'm writing a C# wrapper around a native dll that uses opaque pointers to identify resources. A typical example would be something like

typedef struct session session;
typedef struct track track;

void* sessionCreate(int arg, session** sess);
void  sessionRelease(session** sess);
track* sessionGetTrack(session* sess, int index);
void trackAddRef(track* trk);
void trackRelease(track* trk);
int  trackGetLength(track* trk);

In my wrapper, I've created C# classes corresponding to the different opaque types, with member functions corresponding to the various functions using the different opaque types.

This is fine. There are also callbacks from the dll, for example

void(* track_changed )(track *trk, bool changedExternally);

In order to map from the static delegate that handles the callback to the object that corresponds to the handle supplied, I'm using a static dictionary of WeakReferences (IntPtr/SafeHandle as key, object reference as aata) in each of my classes.

So what is the right way to approach removing entries from the static dictionary? I'm writing library code and cannot rely on my clients to Dispose my objects. Should the I put the code in the finalizer?

Or is there a better way to manage the correspondence between the static callbacks and my object instances?

Upvotes: 0

Views: 370

Answers (1)

Jon
Jon

Reputation: 437386

Your clients really should (indeed I would prefer to say must) dispose of your objects since they are IDisposable, just like they do with other BCL classes.

In any case a bog-standard implementation of the dispose/finalize pattern should cover all bases. There is more related discussion here.

Upvotes: 2

Related Questions