ryrich
ryrich

Reputation: 2204

integer handle to memory address C#

My main purpose in doing this conversion is to create an object in C# based off of a memory address...would it be too hack-ish (or totally incorrect/stupid)? If so, is there a better way in doing this?

Something like this:

int app_handle = 920663024; // corresponds to memory location 0x36E033F0
string app_handle_converted_to_hex = decValue.ToString("X");
MyAppClass *newApp = (MyAppClass *)app_handle_converted_to_hex;

Also, is this possible to do at all without the use of pointers?

Upvotes: 0

Views: 901

Answers (2)

ryrich
ryrich

Reputation: 2204

I was able to figure it out based off of existing code in my application (many thanks to Romoku for mentioning Marshal)

My completed code looks like:

int handle = 920663024; // integer pointer corresponding to memory location 0x36E033F0
IntPtr app_handle = helper.GetAppPtr(handle) // gets IntPtr based off of handle
object obj = Marshal.GetObjectForIUnknown(app_handle);
MyAppClass newApp = obj as MyAppClass;

Works like a charm!

Upvotes: 0

Dustin Kingen
Dustin Kingen

Reputation: 21245

You're going to want to use Marshal.PtrToStructure which assumes a sequential layout.

Take a look at the example at the bottom of the page.

This code assumes 32-bit compilation. Before using a 64-bit compiler, replace IntPtr.ToInt32 with IntPtr.ToInt64.

[StructLayout(LayoutKind.Sequential)]
public class INNER
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst =  10)]
    public string field1 = "Test";
}   

[StructLayout(LayoutKind.Sequential)]
public struct OUTER
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst =  10)]
    public string field1;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst =  100)]
    public byte[] inner;
}

[DllImport(@"SomeTestDLL.dll")]
public static extern void CallTest( ref OUTER po);

static void Main(string[] args)
{
    OUTER ed = new OUTER();
    INNER[] inn = new INNER[10];
    INNER test = new INNER();
    int iStructSize = Marshal.SizeOf(test);

    int sz =inn.Length * iStructSize;
    ed.inner = new byte[sz];

    try
    {
        CallTest( ref ed);
    }
    catch(Exception e)
    {
        Console.WriteLine(e.Message);
    }

    IntPtr buffer = Marshal.AllocCoTaskMem(iStructSize*10);
    Marshal.Copy(ed.inner,0,buffer,iStructSize*10);

    int iCurOffset = 0;

    for(int i = 0; i < 10; i++)
    {
        inn[i] = (INNER)Marshal.PtrToStructure(new IntPtr(buffer.ToInt32() + iCurOffset),typeof(INNER) );
        iCurOffset += iStructSize;
    }

    Console.WriteLine(ed.field1);
    Marshal.FreeCoTaskMem(buffer);
}

Upvotes: 1

Related Questions