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

Home Posts Topics Members FAQ

GC and pinned pointers

Another thread mentioned non-Pinned pointers as a possible reason for an
Interop bug. I'd like to find out more about how this comes about. I
presume that the Garbage Collector makes a sweep, decides to realloc
memory that is not pinned, and that the unmanaged code's pointer becomes
invalid.

How often does the GC run, given a reasonably large app running on
a P4 300ghz with over 1 gig ram? I would have thought that it did not
need to run often at all.

Is there any other possible cause for the unpinned pointer problems?
Nov 17 '05 #1
11 1474
_BNC wrote:
Another thread mentioned non-Pinned pointers as a possible reason for an
Interop bug. I'd like to find out more about how this comes about. I
presume that the Garbage Collector makes a sweep, decides to realloc
memory that is not pinned, and that the unmanaged code's pointer becomes
invalid.
IIRC unmanaged code can only reference pinned objects, the GC is not
allowed to move pinned objects, so the unmanaged pointer does not become
invalid.

How often does the GC run, given a reasonably large app running on
a P4 300ghz with over 1 gig ram? I would have thought that it did not
need to run often at all.


A GC is performed each time your application wants to allocate an object
and generation 0's threshold is reached (something like 256K i think).
So, how often a GC is performed depends on how your application is behaving.

Regards,
Joakim
Nov 17 '05 #2

The number of GC run's depend highly on your usage pattern NOT the systems
CPU performance, if you allocate very frequently, the GC will run very
frequently .
If you don't allocate at all, the GC will not run at all(unless the system
runs low on memory).
You should not care about the number of GC runs, you have to pin the
pointers you pass to unmanaged code that's all.

Willy.

"_BNC" <_B**@nospam.co m> wrote in message
news:p4******** *************** *********@4ax.c om...
Another thread mentioned non-Pinned pointers as a possible reason for an
Interop bug. I'd like to find out more about how this comes about. I
presume that the Garbage Collector makes a sweep, decides to realloc
memory that is not pinned, and that the unmanaged code's pointer becomes
invalid.

How often does the GC run, given a reasonably large app running on
a P4 300ghz with over 1 gig ram? I would have thought that it did not
need to run often at all.

Is there any other possible cause for the unpinned pointer problems?

Nov 17 '05 #3
On Wed, 12 Jan 2005 23:05:39 +0100, "Willy Denoyette [MVP]"
<wi************ *@pandora.be> wrote:

The number of GC run's depend highly on your usage pattern NOT the systems
CPU performance, if you allocate very frequently, the GC will run very
frequently .
If you don't allocate at all, the GC will not run at all(unless the system
runs low on memory).
You should not care about the number of GC runs, you have to pin the
pointers you pass to unmanaged code that's all.

Willy.


Thanks for your reply, Willy. I'm not being stubborn about pinning
pointers...I'm trying to figure out if I missed one somewhere. Or maybe
it's another problem entirely, I don't know. I'm not doing that many
memory allocs. I initially didn't figure that the GC would be the
culprit, but since problems turn up only when the program is stressed, it
would seem a likeley suspect. The smaller test models that I've worked up
run fine, of course.

I'm still trying to get a handle on the subtleties of the
managed-to-unmanaged bridge. Much of this seems counterintuitiv e to me.
For instance, the MSDN code that uses a similar method:

http://msdn.microsoft.com/library/de...nagedtypes.asp

does not __pin the pointer to the unmanaged struct (see constructor:
"city = new CITY;"). I'm trying to figure out why that pointer does not
need to be pinned.

I started my original model from code in a wrox book
"Visual C++.NET: a primer for C++ Developers" (Aravind Corera, etc,
ISBN 1861005962). which outlines the approach of using 'concentric'
classes layered around internal unmanaged code (Center = DLL, then
unmanaged C++ wrapper, then managed C++ wrapper, then C#). They
do not pin the pointer to the unmanaged C++ wrapper either.

I would have gone with PInvoke from the start, but the central DLL is such
a mess, with tons of obscure structs and defined data types, that it
seemed more logical to encapsulate the ugly stuff on the unmanaged side of
the fence.

I'm afraid that by the time I get a good handle on how the interim
layering works, Whidbey will have made it obsolete and my project will be
over. <g> (IOW, the real problem is a stupid typo somewhere)

_B
Nov 17 '05 #4
_BNC wrote:
I'm still trying to get a handle on the subtleties of the
managed-to-unmanaged bridge. Much of this seems counterintuitiv e to me.
For instance, the MSDN code that uses a similar method:

http://msdn.microsoft.com/library/de...nagedtypes.asp

does not __pin the pointer to the unmanaged struct (see constructor:
"city = new CITY;"). I'm trying to figure out why that pointer does not
need to be pinned.


I can try to help explain this part. The garbage collector ignores
unmanaged objects altogether; it will not move them, it will not free
them, and they cannot be pinned. If you define a managed (__gc) C++
class that contains pointers to unmanaged objects, the garbage collector
simply ignores these pointers. It is the job of that class's destructor
to deallocate the objects properly, and GC invokes this destructor at
the appropriate time. More generally, *managed code* is able to deal
with and contain *unmanaged objects* without much of a problem.

It is going in the other direction that pinning comes into play - if you
use *unmanaged code* to deal with pointers to *managed objects*. In this
case, GC does know about the object, and what it doesn't know about are
the unmanaged pointers to it. This prevents it from updating these
pointers after moving the object. Also, if only unmanaged pointers to an
object exist (which it doesn't know about) it will assume the object can
be freed. Pinning prevents this as well. Unfortunately, excessive
pinning also inhibits the efficiency of the collector, because it's
harder to find space to allocate in a highly fragmented memory pool.
--
Derrick Coetzee, Microsoft Speech Server developer
This posting is provided "AS IS" with no warranties, and confers no
rights. Use of included code samples are subject to the terms
specified at http://www.microsoft.com/info/cpyright.htm
Nov 17 '05 #5
On Thu, 13 Jan 2005 19:11:35 -0500, "Derrick Coetzee [MSFT]"
<dc******@onlin e.microsoft.com > wrote:
_BNC wrote:
I'm still trying to get a handle on the subtleties of the
managed-to-unmanaged bridge. Much of this seems counterintuitiv e to me.
For instance, the MSDN code that uses a similar method:

http://msdn.microsoft.com/library/de...nagedtypes.asp

does not __pin the pointer to the unmanaged struct (see constructor:
"city = new CITY;"). I'm trying to figure out why that pointer does not
need to be pinned.
I can try to help explain this part. The garbage collector ignores
unmanaged objects altogether; it will not move them, it will not free
them, and they cannot be pinned. If you define a managed (__gc) C++
class that contains pointers to unmanaged objects, the garbage collector
simply ignores these pointers. It is the job of that class's destructor
to deallocate the objects properly, and GC invokes this destructor at
the appropriate time. More generally, *managed code* is able to deal
with and contain *unmanaged objects* without much of a problem.


That makes sense. Still, it seems like the example code effectively
allocs the inner unmanaged struct and maintains that pointer to that
struct without having to be pinned. I could swear that I've seen
equivalent pointers pinned in some example code, but I guess this will
make sense after it sinks in.

Now I've got to look for another cause for my problems though, cause I'm
allocing a block of ram in an unmanaged module, and the only thing that
the managed code does is pass the pointer to it to another unmanaged
class. No allocs are done by the managed code, and my understanding
is that the pointer itself is safe, being a low-level item.
It is going in the other direction that pinning comes into play - if you
use *unmanaged code* to deal with pointers to *managed objects*. In this
case, GC does know about the object, and what it doesn't know about are
the unmanaged pointers to it. This prevents it from updating these
pointers after moving the object. Also, if only unmanaged pointers to an
object exist (which it doesn't know about) it will assume the object can
be freed. Pinning prevents this as well.
A lucid explanation, Derrick.
Unfortunately, excessive
pinning also inhibits the efficiency of the collector, because it's
harder to find space to allocate in a highly fragmented memory pool.


I've heard that pinned pointers can effectively slow down the managed
code by a factor of 25 (!) so I've been trying to avoid them.

_B
Nov 17 '05 #6
> Still, it seems like the example code effectively
allocs the inner unmanaged struct and maintains that pointer to that
struct without having to be pinned.
That's true; in fact, there's no point in pinning a pointer to an unmanaged
object, because the GC doesn't know about these objects and won't move them,
and ignores the pointer. Such blocks of memory are outside its control, just
like a block allocated in an unmanaged program. They are, effectively,
already pinned.
I could swear that I've seen equivalent pointers pinned in some example code [ . . . ]

This may have been a pointer to a managed object, or it might have been a
mistake. It might let you create pinned pointers to unmanaged objects,
although this is pointless, since they're already "pinned."
Now I've got to look for another cause for my problems though, cause I'm
allocing a block of ram in an unmanaged module, and the only thing that
the managed code does is pass the pointer to it to another unmanaged
class. No allocs are done by the managed code, and my understanding
is that the pointer itself is safe, being a low-level item.
The Framework shouldn't interfere with unmanaged-to-unmanaged interactions,
as a rule. It sounds like your application has some very subtle problems.
I'm not sure where to tell you to start, but if you can find an alternative
to interfacing managed and unmanaged code using a mixed-code DLL, this might
be the simplest way to go. For example, I once did something similar to this
where in the end I ended up driving the C module through a command-line
interface and input/output files. You may also try using PInvoke to call
directly from the managed to the unmanaged code. In C# this is done with the
DllImport attribute; see an example here:

http://msdn.microsoft.com/library/de...okevisualc.asp
I've heard that pinned pointers can effectively slow down the managed
code by a factor of 25 (!) so I've been trying to avoid them.


The main problem is that it slows down garbage collection cycles and
allocations a great deal if you use many pinned pointers at once, and the
larger the objects you pin the worse the effect. Pinning some small things
here and there is relatively harmless.
--
Derrick Coetzee, Microsoft Speech Server developer
This posting is provided "AS IS" with no warranties, and confers no rights.
Nov 17 '05 #7
On Fri, 14 Jan 2005 10:59:19 -0800, "Derrick Coetzee [MSFT]"
<dc******@onlin e.microsoft.com > wrote:
... there's no point in pinning a pointer to an unmanaged
object, because the GC doesn't know about these objects and won't move them,
and ignores the pointer. Such blocks of memory are outside its control, just
like a block allocated in an unmanaged program. They are, effectively,
already pinned.
That finally makes sense. I've assumed that if the alloc was done within
managed code, that it would be subject to garbage collection. It's one of
those subtleties that was not clear in the docs that I've read.
Now I've got to look for another cause for my problems though, cause I'm
allocing a block of ram in an unmanaged module, and the only thing that
the managed code does is pass the pointer to it to another unmanaged
class. No allocs are done by the managed code, and my understanding
is that the pointer itself is safe, being a low-level item.


The Framework shouldn't interfere with unmanaged-to-unmanaged interactions,
as a rule. It sounds like your application has some very subtle problems.
I'm not sure where to tell you to start, but if you can find an alternative
to interfacing managed and unmanaged code using a mixed-code DLL, this might
be the simplest way to go.


I've heard of subtle bugs in .NET mixed mode in general. It's frustrating
in that so much work went into the mixed mode bridge, and it's difficult
to trace problems. Smaller, or unstressed models of the code work fine.
I thought maybe it was a task prioritization thing, as the access to the
mixed mode code occurs in a thread. Strangely enough, increasing the
thread priority makes the code *less* reliable. I'm not getting runtime
errors or exceptions--just wrong results. Very counterintuitiv e.
For example, I once did something similar to this
where in the end I ended up driving the C module through a command-line
interface and input/output files. You may also try using PInvoke to call
directly from the managed to the unmanaged code. In C# this is done with the
DllImport attribute; see an example here:

http://msdn.microsoft.com/library/de...okevisualc.asp
Thanks for the link, Derrick. I first considered PInvoke, but thought
that mixed mode would be better for this app (see below). However, if the
..NET mixed-mode DLL has inherent problems, as in:

http://msdn.microsoft.com/library/de...ingProblem.asp

...then I suppose I'll have to give up on it. Unfortunately, the inner C
DLL is very messy, with lots of typedefs and structs that would be tough
to marshal via PInvoke. The fallback plan may be to encapsulate the C DLL
in an unmanaged C++.NET class to simplify the interface, and use PInvoke
to access that.

I've essentially done the encapsulation part already in the course of
writing the mixed-mode DLL, so I suppose I could start from there and
just PInvoke the encapsulating class.

I've also written a completely unmanaged version of the code which works
fine under run-time stress. In other words, I've got lots of clues, all
pointing in different directions. <g>
Derrick Coetzee, Microsoft Speech Server developer


Thanks for your perspective, Derrick. My understanding of the
managed-to-unmanaged transition is improving.

Re MS Speech server: I know you're probably more involved with the
ASP-related side of the MS Speech SDK, but I'm curious about MS's 'local'
speech SDK. I haven't had much luck with the 5.1 SDK under .NET. There
was a v5.2 mentioned somewhere that had more .NET support, but it seems to
have disappeared. Do you happen to know if anything new is imminent?

_B

Nov 17 '05 #8
_BNC wrote:
I've heard of subtle bugs in .NET mixed mode in general. It's frustrating
in that so much work went into the mixed mode bridge, and it's difficult
to trace problems. Smaller, or unstressed models of the code work fine.
I thought maybe it was a task prioritization thing, as the access to the
mixed mode code occurs in a thread. Strangely enough, increasing the
thread priority makes the code *less* reliable. I'm not getting runtime
errors or exceptions--just wrong results. Very counterintuitiv e.
[ . . . ]
However, if the .NET mixed-mode DLL has inherent problems, as in:

http://msdn.microsoft.com/library/de...ingProblem.asp

..then I suppose I'll have to give up on it.
Although you don't experience deadlock, corruption is possible if
static data such as globals and class variables are not initialized
correctly, which is a possible effect of the loading problem. It also
seems to fit your experience of having problems only during stress
conditions:

"[D]eadlock situations are always possible with mixed DLLs, even though
they are often quite rare in practice. The worst part of this is that
mixed DLLs that happen to work on most systems can begin deadlocking if
the system is stressed, the image is signed [...], hooks are installed
into the system, or the behavior of the runtime changes through service
packs or new releases."

Unfortunately it's impossible to avoid the loading problem in any
released versions of the .NET Framework so far. If it's important that
your program starts correctly without deadlock, this may already be
enough reason to avoid using mixed DLLs.

If you still want to try to make the mixed DLL work, make sure you've
followed the steps of this KB to remove the entry point and manually
initialize all static data:

http://support.microsoft.com/Default.aspx?id=814472
Unfortunately, the inner C
DLL is very messy, with lots of typedefs and structs that would be tough
to marshal via PInvoke. The fallback plan may be to encapsulate the C DLL
in an unmanaged C++.NET class to simplify the interface, and use PInvoke
to access that.
This seems workable. For transmitting larger amounts of data, you may
also consider using shared memory, shared files, or even local network
communication.
I've also written a completely unmanaged version of the code which works
fine under run-time stress. In other words, I've got lots of clues, all
pointing in different directions. <g>
If you don't have a compelling reason to provide a .NET interface, such
as language interoperabilit y, you may consider simply using your
unmanaged interface, and eschewing .NET altogether.
Re MS Speech server: [ . . . ] There
was a v5.2 mentioned somewhere that had more .NET support, but it seems to
have disappeared. Do you happen to know if anything new is imminent?


I'm afraid I'm involved only with the server product, and so I don't
know about this, but I will try to contact someone who works on the
Speech SDK to answer your question.
--
Derrick Coetzee, Microsoft Speech Server developer
This posting is provided "AS IS" with no warranties, and confers no rights.
Nov 17 '05 #9
On Sat, 15 Jan 2005 20:24:10 -0500, "Derrick Coetzee [MSFT]"
<dc******@onlin e.microsoft.com > wrote:
If you don't have a compelling reason to provide a .NET interface, such
as language interoperabilit y, you may consider simply using your
unmanaged interface, and eschewing .NET altogether.


Wow. I would agree wholeheartedly. What was .NET created to solve in
the first place? Shitty programmers! So, if you're not a shitty
programmer, you don't need managed code.

BTW, VC.NET, at least 2003, allows you to create actual, real C and
C++ programs, for the most part. (But don't expect C99 support any
time this millennium).

--
Sev
Nov 17 '05 #10

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

Similar topics

1
4133
by: goyal | last post by:
Hi, Is there a way to find out which tables/indexes/packages/functions have been pinned in the database? Thanks in advance. Cheers, Sachin
0
1719
by: kiplring | last post by:
I'm using managed directx. I made a KeyFrameInterpolator object. And get a exception above. I think it is because GC reconize KeyFrameInterpolator object as Pinned object. So I added next line. --------- System.Runtime.InteropServices.GCHandle.Alloc(myKeyFrameInterpolator,System.Runtime.InteropServices.GCHandleType.Normal); --------- I set it as Normal. But I got the same Exception. I don't know what the Handle means.(Handle is not...
2
1435
by: Mark Oliver | last post by:
Hi, I want to pass a reference to a char type to a class constructor, then read/write to the passed char later in my code. Are the below Asserts right? Thanks, Mark
7
3886
by: _BNC | last post by:
Another thread mentioned non-Pinned pointers as a possible reason for an Interop bug. I'd like to find out more about how this comes about. I presume that the Garbage Collector makes a sweep, decides to realloc memory that is not pinned, and that the unmanaged code's pointer becomes invalid. How often does the GC run, given a reasonably large app running on a P4 300ghz with over 1 gig ram? I would have thought that it did not need to...
3
1257
by: Ben Schwehn | last post by:
If I pin a member of a garbage collected structure, can I safely assume that the entire struct is pinned? I use something like that: (new whidbey syntax, but that shouldn't make a difference): public ref struct MyStruct {
1
1282
by: Lance Orner | last post by:
I wrote this letter to a colleague, and I thought I'd share it here: --- We had a problem with pointers being passed between managed C++ and unmanaged C++ code, but it only occurred once in every 2000-3000 calls. There were some String* objects in the managed code, which were marshalled into IntPtr* objects. This was cast into a const char __pin* and passed to some unmanaged C++ code. When the problem would occur, the breakpoint...
1
1789
by: Pierre | last post by:
Hi everyone; I have a class with several members and I pin the first reference field in a function; public ref struct MyClass { String str1; List<MySubClass ^^subObjects; ....
1
2351
by: Crash | last post by:
..Net - All versions I have Essential .Net Vol 1 (Don Box) and the Jeffrey Richter articles on the .NET heap - they are both excellent reads. But I am still unclear on the big pinned memory question: Pinned memory: if I have a block of pinned memory active on the heap when a garbage collection occurs where does the garbage collector set the NextObj pointer? Can the garbage collector/heap allocator logic work around the pinned block...
16
3134
by: Atmapuri | last post by:
Hi! It would be great, if the pinned arrays would be garbage collectable. This would greatly reduce the amount of copy back and forth the managed and unmanaged memory. I cant think of a single reason, why the GC should not allow this. It would be also great, if the memory could already be allocated as pinned:
2
2494
by: ChaosMageX | last post by:
I copied some code from a Mono 2.4 library to use in my own application. I'm getting a problem because one of the variable declarations involves the keyword "pinned" between the identifier and the instance name. public override unsafe void PutBytes(byte dest, int destIdx, double value) { base.Check(dest, destIdx, 8); byte* pinned numPtr = $(dest); long* numPtr2 = (long*) &value; *((long*) numPtr) = numPtr2; numPtr =...
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
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10147
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...
1
10090
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9949
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
8971
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...
0
5380
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.