整数句柄到内存地址C#

lsint 发布于 2019-03-09 c# 最后更新 2019-03-09 14:35 2 浏览

我在做这种转换的主要目的是在C#中创建一个基于内存地址的对象......会不会太黑客(或完全不正确/愚蠢)?如果是这样,这样做有没有更好的方法? 像这样的东西:

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;
另外,如果不使用指针,可以做到这一点吗?
已邀请:

yut

赞同来自:

您将要使用假定顺序布局的Marshal.PtrToStructure。 看一下页面底部的示例。

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);
}

gcum

赞同来自:

我能够根据我的应用程序中的现有代码来解决这个问题(非常感谢Romoku提到了Marshal) 我完成的代码如下所示:

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;
奇迹般有效!