2013-04-11 31 views
0

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

而且,这可能在所有做不使用指针的?

+6

你想达到什么目的?这坚决抵制“正常”的C#旨在。 – 2013-04-11 16:11:26

+0

只有时间做这样的演员才能与本机代码进行互操作,即使这样,通常也有更好的解决方案。您的具体示例看起来完全失败。 – CodesInChaos 2013-04-11 16:11:44

+5

切勿将int32用于内存地址,请改为使用IntPtr。 – ken2k 2013-04-11 16:12:34

回答

1

你会想要使用Marshal.PtrToStructure,它假设顺序布局。

看看页面底部的例子。

此代码假定32位编译。在使用64位编译器之前,将IntPtr.ToInt32替换为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); 
} 
0

我能弄明白基于关在我的应用程序的现有代码(非常感谢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; 

奇迹般有效!