Sanity Check; C library memory management through through C#

A

Arthur Mnev

Does anyone know if there are any ramifications of using crtdll.dll
from within the framework?

[System.Runtime.InteropServices.DllImport("crtdll.dll")] extern public
static IntPtr malloc(Int32 size_t);

and simmilar will work fine; looking at the source of CLR itself:

ILNativeInt _IL_Marshal_AllocHGlobal(ILExecThread *_thread,
ILNativeInt cb)
{
if(UnmanagedOK(_thread))
{
/* Use the underlying system "calloc", because
"ILCalloc"
may have been redirected elsewhere */
void *ptr = (void *)calloc((unsigned)cb, 1);
if(ptr)
{
return (ILNativeInt)ptr;
}
ILExecThreadThrowOutOfMemory(_thread);
}
return 0;
}

we can can see the functions being used.
To prevent some of the questions; working with real-time buffers i do
need the functions and no, i do not want to implement it in C++ as it
is a very small portion of the project.

What i dont know is where does CLR allocate the memory when low level
is called. Is it local heap to CLR (and thereby possible compromise of
GC's efficiency) or is it separate heap that CLR hosts for unmanaged
functionality.

tia

P.S. While doing some of the testing I got something very puzzling;
declaring functions such as calloc() and free() through above method
and then running 1mln allocations & free i found out that Internal
Marshal.AllocHGlobal & Marshal.FreeHGlobal seems to work at about 5
times faster.
in high resolution timer allocating 20k per loop
~3030000 for Marshal class functions
~12680000 for C functions
for comparison; allocating a single managed structure with the same
amount of bytes (Size = 20k)
~32580000.
Clearly Some of the internal functions win the question is why. I
tried both libraries crtdll.dll and msvcrt.dll

The logic that I'm following: if managed function executes the same C
library, why in the world is direct call slower??

Any responses will be highly appreciated, even lunacy will not be
frown on...
 
M

Mattias Sjögren

Arthur,
and simmilar will work fine; looking at the source of CLR itself:

ILNativeInt _IL_Marshal_AllocHGlobal(ILExecThread *_thread,
ILNativeInt cb)

Which CLI implementation is this? The CLR's AllocHGlobal
implementation calls kernel32!LocalAlloc, no CRT functions.

What i dont know is where does CLR allocate the memory when low level
is called.

What allocation are you referring to, specifically?



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top