[Mono-devel-list] malloc and free on CLI

Paolo Molaro lupus at ximian.com
Mon Jul 18 05:26:29 EDT 2005


On 07/16/05 Kornél Pál wrote:
> I think to get te better berformance you should implement heap functionality
> natively. But not using P/Invoke because it's inefficient. You should rater
> use InternalCalls. Use mono/mono/metadata/icall.c and [MethodImplAttribute
> (MethodImplOptions.InternalCall)].
> 
> This will result in a very good performance because there will be no
> marshaling.

This is completely incorrect: dllimporting malloc() doesn't need any
marshalling, so using icalls would be the same speed as pinvoke, but
you'd have the disadvantage of having to change the mono runtime and depend
on a specific version. Icalls are completely out of the question
as an implementation for this.

The managed C compiler should implement two patterns, both of which
are required:
1) map a function call to a dllimport
2) map a function call to corlib/System/ManagedLibc methods

The first way is needed to be able to compile programs without
needing to compile every dependent lib with the managed C compiler.
The second option is needed to be able to compile an optimized
managed libc. For example, consider calls to strcmp(): using
dllimport (or icalls) will have a big performance impact, so the
function should be implemented in managed land (wether in C or C#
doesn't matter). But, for example, calls to malloc should still be
dllimported, otherwise you won't be able to use in the managed C
program native libraries that use it (think when a library
returns a pointer you need to call free() on).
You also need to be able to implement some of the managed libc
using corlib or system methods, so that the program is more portable
and it integrates better with the rest of the runtime.

Both mappings could be implemented with creative uses
of gcc's attributes. In your compiler's headers, you'd have
declarations like:

int strcmp(const char *s1, const char *s2) __attribute__((managed("ManagedLibc(Strings::strcmp(byte*,byte*))")));

This will instruct the compiler to emit a manged call to the
Strings::strcmp(byte*,byte*) method inside ManagedLibc.

Note that you want to have also malloc redirected to ManagedLibc,
so in your stdlib.h header, you'll have:

void *malloc(size_t size) __attribute__((managed("ManagedLibc(Stdlib::malloc(IntPtr))")));

while in the implementation (if you write this part of ManagedLibc in 
managed C), you'd have something like:

void *malloc(size_t size) __attribute__((dllimport("libc")));

instead of:

void *malloc(size_t size) {
	... malloc code...
}

lupus

-- 
-----------------------------------------------------------------
lupus at debian.org                                     debian/rules
lupus at ximian.com                             Monkeys do it better



More information about the Mono-devel-list mailing list