Skip to content

NativeLibrary documentation: Cache result of System.Runtime.InteropServices.DllImportResolver  #46463

@badcel

Description

@badcel

I found the discussion about updating the docs regarding NativeLibrary in #41180 (comment). As i did not want to hijack the discussion I open this issue to improve the documentation on NativeLibrary.

@jkotas I just wanted to raise the question if it is valid to cache the IntPtr to an assembly in the given resolver of SetDllImportResolver (System.Reflection.Assembly assembly, System.Runtime.InteropServices.DllImportResolver resolver);?

I think this could be an important information in the docs because it is very tempting to cache the found IntPtr of NativeLibrary.TryLoad but it is not clear from the documentation if this is valid in all cases.

Sample code:

private static IntPtr DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
    if (cache.TryGetValue(libraryName, out var cachedLibHandle))
        return cachedLibHandle;

   if (NativeLibrary.TryLoad(GetOsDependentLibraryName(libraryName), assembly, DllImportSearchPath.LegacyBehavior, out var libHandle))
   {
        cache[libraryName] = libHandle;
        return libHandle;
   }

    return IntPtr.Zero;
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions