views:

71

answers:

1

Hello,

In a C# project, I need to pass object parameters by putting references in a structure. i.e. I have a structure passed to a dispatcher

struct SOMESTRUCT
{
    public int lpObject;
}

Where lpObject holds a pointer to a custom object like

class SomeClass
{
    private string foo;
}

And the SOMESTRUCT structure is passed from method to method to finally reach my code. I cannot modify the execution flow nor the strange SOMSTRUCT system, so I guessed the only solution was to cast my object to a pointer like this :

var myObject = new SomeClass();
GCHandle GC = GCHandle.Alloc(myObject, GCHandleType.Pinned);
int myRef = GC.AddrOfPinnedObject().ToInt32();
GC.Free();

SOMESTRUCT struct;
struct.lpObject = myRef;
someMethod(struct);

However, I can't figure out how to retrieve the myObject members from the lpObject fields. Something like this:

SomeClass myObject = CastPointerToObject(struct.myRef) as SomeClass;

Is there a way to do it, or is it impossible ? How can I tell the garbage collector to handle the object ? Should I create a new Garbage-collected object and copy the data field by field ?

TYIA,

+2  A: 

Do you mean you want to cast the returned pointer back to a struct?

Similar to:

lvHitTestInfo = (LVHITTESTINFO)Marshal.PtrToStructure(lP, typeof(LVHITTESTINFO));

Where lvHitTestInfo is a structure and lp a pointer.

Or i didn't understand your question properly. Maybe you can explain more (more complete code sample).

Jeroen
Yes and no. I want to cast the returned pointer to an object. I will add more details to my question.
kbok
I didn't noticed that this methods works also with objects. This is what I was looking for. Thank you for your help !
kbok
I've never gone there but to know if that's possible you need to give an exact description of what is actually returned. What exactly does the pointer point to.See, if you're interacting with unmanaged code it's very unlikely you will be able to cast to a managed object. There's no way knowing what goes where.
Jeroen