Alex Rivera | Logout

How to instance a C# class in UNmanaged memory? (Possible?)

Asked 2012-05-29T13:21:39.770
13

UPDATE: There is now an accepted answer that "works". You should never, ever, ever, ever use it. Ever.


First let me preface my question by stating that I'm a game developer. There's a legitimate - if highly unusual - performance-related reason for wanting to do this.


Say I have a C# class like this:

class Foo
{
    public int a, b, c;
    public void MyMethod(int d) { a = d; b = d; c = a + b; }
}

Nothing fancy. Note that it is a reference type that contains only value types.

In managed code I'd like to have something like this:

Foo foo;
foo = Voodoo.NewInUnmanagedMemory<Foo>(); // <- ???
foo.MyMethod(1);

What would the function NewInUnmanagedMemory look like? If it can't be done in C#, could it be done in IL? (Or maybe C++/CLI?)

Basically: Is there a way - no matter how hacky - to turn some totally arbitrary pointer into an object reference. And - short of making the CLR explode - damn the consequences.

(Another way to put my question is: "I want to implement a custom allocator for C#")

This leads to the follow-up question: What does the garbage collector do (implementation-specific, if need be) when faced with a reference that points outside of managed memory?

And, related to that, what would happen if Foo had a reference as a member field? What if it pointed at managed memory? What if it only ever pointed at other objects allocated in unmanaged memory?

Finally, if this is impossible: Why?


Update: Here are the "missing pieces" so far:

#1: How to convert an IntPtr to an object reference? It might be possible though unverifiable IL (see comments). So far I've had no luck with this. The framework seems to be extremely careful to prevent this from happening.

(It would also be nice

Edit
Report

2 Answers

0

Nothing like that is possible. You can access managed memory in unsafe context, but said memory is still managed and subject to GC.

Why?

Simplicity and security.

But now that I think about it, I think you can mix managed and unmanaged with C++/CLI. But I'm not sure about that, because I never worked with C++/CLI.

answered 2012-05-29T13:24:17.983
0

I don't know a way to hold a C# class instance in the unmanaged heap, not even in C++/CLI.

answered 2012-05-29T13:49:30.350

Your Answer