-1

我引用了内存中的值,但我无法得到这个值并将他投射到我的类型上。请告诉我我应该写什么,这样我才能获得价值,或者说我为什么不能这样做

我的例子:

ListItem<string> item = new ListItem<string>("hell to world"); //ListItem<T> is class
unsafe
{
   TypedReference itemRef = __makeref(item);
   IntPtr reference = **(IntPtr**)&item;
   long address = (long)reference;
}

我可以使用__refvalue. 此方法需要TypedReference并键入您想要转换的值。这项工作,但我不知道如何TypedReferencevoid*,IntPtrlong. 我希望有人帮助我

UPD:我写了一个简单的双向列表,希望它至少比默认列表快一点。好吧,和往常一样,双向列表中有指向下一个和前一个元素的指针。但是我使用了同一类的对象而不是指向该对象的指针,所以我尝试使用指针和内存。

UPD:我写这篇只是出于个人兴趣,仅此而已

4

1 回答 1

1

尝试使用Marshal.PtrToStructure方法https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.ptrtostructure?view=netframework-4.8#System_Runtime_InteropServices_Marshal_PtrToStructure_System_IntPtr_System_Type_

如果它不是你想要的,你可以看到另一个MarshalMarshalEx方法。创建此类是为了在 C# 中使用指针。

于 2020-03-18T15:45:18.393 回答