Re: Garbage collectable pinned arrays!

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



"Atmapuri" <janez.makovsek@xxxxxxx> wrote in message news:DC92D886-0A02-44D9-8450-33C1FE91AA05@xxxxxxxxxxxxxxxx
Hi!

No, you don't because somehow you must pin the object to prevent premature collection. It's not because an object that is not pinned, is not referenced by the unmanaged code.

Consider following sample:

int[] ia = new ia[200000]; // large object stored on the LOH at a fixed location (not moveable.
UnmanagedFunctionThatTakesAnArrayOfInts(ia);

if the interop layer would not pin the array, the GC would be free to collect the object and as such invalidate the pointer you have passed to unmanaged code. The reason for this is that the JIt doesn't know about unmanaged code, as a result he *marks* the reference "ia" as a candidate for collection (signals the GC that the object ia refers to may be collected at the moment of the call.

That is not the case, if you put

GC.KeepAlive(ai);

at the end of your code, which not costs "Nothing" (!!!)


Oh, and you forget one of these KeepAlives and hell breaks loose. And again why would you need this for, the arguments passed through PInvoke are protected when needed for the duration of the call .


Willy.

.



Relevant Pages

  • Re: C# using ActiveX control.
    ... We proberbly all know the issues with CDO and managed code. ... Would I be able to reference my custom objects in an ActiveX in the managed ... I've read in various post that wrapping the component in an ActiveX EXE ... objects being referenced by unmanaged code. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: C# using ActiveX control.
    ... the things you need to watch out for are related to managed objects being referenced by unmanaged code. ... For example, a reference that might be passed to a managed callback executed by the unmanaged code; the managed reference isn't useful to the unmanaged code, but that's where it's being kept until it's used again by managed code. ... Sometimes it's appropriate just to store the reference in a non-local variable (class static member, or an instance member if you know that instance will remain reachable). ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: How to set Lyrics and title from code
    ... zilch experience in unmanaged code. ... You need to compile the "managed" sample in the SDK, ... add a reference to the wrapper DLL. ...
    (microsoft.public.windowsmedia.sdk)
  • Re: .Net not relevant
    ... > Some people will say "unmanaged code". ... That must be a reference to ... ROTFLMAO ... Prev by Date: ...
    (borland.public.delphi.non-technical)
  • Re: .Net not relevant
    ... > What is your opinion? ... Some people will say "unmanaged code". ... That must be a reference to those ... pesky warnings that I turned off in Delphi 7 some three years ago. ...
    (borland.public.delphi.non-technical)