c# - Attempted to read or write protected memory when using reflection to call dll functions -


i have made plugin system uses reflection call functions in plugin. plugin has implement iplugin interface used. in application uses plugins plugin instance created following code:

    assembly currentassembly = assembly.loadfrom(startinfo.pluginassemblypath);     type[] types = currentassembly.gettypes();     iplugin plugininstance = null;      foreach (type type in types)     {         if (type.fullname == startinfo.plugintypename)         {             plugininstance = (iplugin)activator.createinstance(type);         }     }      if (plugininstance == null)     {         throw new exception("plugin loader error: not instantiate plugin: " + startinfo.tostring());        }      return plugininstance; 

i have made plugin uses unmannaged dll's. when call iplugin interface functions in test project in plugin solution works fine. when call plugin via plugin instance made in code shown above system.accessviolationexception: attempted read or write protected memory error when calling functions in unmannaged dll's.

the unmannaged dll's c++ dll's made third party. tried enabling native code debugging not have .pdb files.

i not sure why happening, because of reflection? or can there other causes?

edit: in stack can see unmannaged function being called:

[marshalas(unmanagedtype.lpstr)] private readonly stringbuilder sb = new stringbuilder(256);  [dllimport("x.dll", entrypoint = "xlib")] static extern int _xlib(int a1, int a2, int a3, int a4, int a5, int a6, [out]stringbuilder str); 

the exception thrown when calling _xlib function.

edit: somewhere in _xlib function following function called:

handle = x_open(); 

which in other dll , defined as:

dllexport x_handle *x_open(); 

as in handle used like:

"%s", handle->x.string 

the exception thrown. still not understand why working in test project , not when using in app plugin.

maybe have pin stringbuilder allow unmanaged code interact it.

pinned object 1 not allowed move. garbage collector compacting memory in moves objects "one or more clusters". create large chunks of free space.

this means if else (outside) has pointer memory address of object, may point random content - object has moved.

pinning object tells gc not move it. useless , makes sense when working pointers - when using pinvoke... , can see pointer stringbuilder instance in _xlib function


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -