C# 内存地址C的整数句柄#

C# 内存地址C的整数句柄#,c#,C#,我进行这种转换的主要目的是基于内存地址在C#中创建一个对象……这会不会太黑客化(或者完全不正确/愚蠢)?如果是,有没有更好的方法 大概是这样的: int app_handle = 920663024; // corresponds to memory location 0x36E033F0 string app_handle_converted_to_hex = decValue.ToString("X"); MyAppClass *newApp = (MyAppClass *)app_hand

我进行这种转换的主要目的是基于内存地址在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;

另外,这是否可以在不使用指针的情况下实现?

您将要使用的是假定顺序布局的指针

看一下页面底部的示例

此代码假定为32位编译。在使用64位编译器之前,请将IntPtr.ToInt32替换为IntPtr.ToInt64

[StructLayout(LayoutKind.Sequential)]
公共阶级内部
{
[Marshallas(UnmanagedType.ByValTStr,SizeConst=10)]
公共字符串field1=“测试”;
}   
[StructLayout(LayoutKind.Sequential)]
公共结构外部
{
[Marshallas(UnmanagedType.ByValTStr,SizeConst=10)]
公共字符串字段1;
[Marshallas(UnmanagedType.ByValArray,SizeConst=100)]
公共字节[]内部;
}
[DllImport(@“SomeTestDLL.dll”)]
公共静态外部无效呼叫测试(参考外部po);
静态void Main(字符串[]参数)
{
外部ed=新的外部();
内尔[]客栈=新内尔[10];
内部测试=新的内部测试();
int iStructSize=Marshal.SizeOf(测试);
int sz=inn.Length*i结构尺寸;
ed.inner=新字节[sz];
尝试
{
呼叫测试(ref ed);
}
捕获(例外e)
{
控制台写入线(e.Message);
}
IntPtr buffer=Marshal.allocTaskMem(iStructSize*10);
封送处理副本(内部,0,缓冲区,iStructSize*10);
int iCurOffset=0;
对于(int i=0;i<10;i++)
{
inn[i]=(内部)Marshal.PtrToStructure(新的IntPtr(buffer.ToInt32()+iCurOffset),typeof(内部));
iCurOffset+=IStroctSize;
}
控制台写入线(ed.field1);
FreeCoTaskMem元帅(缓冲区);
}

我能够根据我的应用程序中现有的代码找出它(非常感谢Romoku提到的
封送

我完成的代码如下所示:

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;

工作起来很有魅力

你想达到什么目标?这与“普通”C#的目标背道而驰。进行此类强制转换的唯一时间是与本机代码互操作,即使这样,通常也有更好的解决方案。您的特定示例看起来完全不正确。请勿将int32用作内存地址,而应使用IntPtr。您的示例指向的托管字符串包含给定的地址作为值,而不是所需的内存位置。这是嵌入式设备(可能还有MemoryMappedFile)中的常见模式
MyAppClass
必须是结构(或顺序类),才能在C#中工作。
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;