Marshal.PtrToStructure Método
Definição
Realizar o marshaling de dados de um bloco de memória não gerenciado para um objeto gerenciado.Marshals data from an unmanaged block of memory to a managed object.
Sobrecargas
| PtrToStructure(IntPtr, Object) |
Obsoleto.
Realizar o marshaling de dados de um bloco de memória não gerenciado para um objeto gerenciado.Marshals data from an unmanaged block of memory to a managed object. |
| PtrToStructure(IntPtr, Type) |
Obsoleto.
Realiza marshal de dados de um bloco não gerenciado de memória para um objeto gerenciado recém-alocado do tipo especificado.Marshals data from an unmanaged block of memory to a newly allocated managed object of the specified type. |
| PtrToStructure<T>(IntPtr) |
[Suporte somente no .NET Framework 4.5.1 e versões posteriores][Supported in the .NET Framework 4.5.1 and later versions] Realiza marshaling de dados de um bloco não gerenciado de memória para um objeto gerenciado recém-alocado do tipo especificado por um parâmetro de tipo genérico.Marshals data from an unmanaged block of memory to a newly allocated managed object of the type specified by a generic type parameter. |
| PtrToStructure<T>(IntPtr, T) |
[Suporte somente no .NET Framework 4.5.1 e versões posteriores][Supported in the .NET Framework 4.5.1 and later versions] Realiza marshaling de dados de um bloco não gerenciado de memória para um objeto gerenciado do tipo especificado.Marshals data from an unmanaged block of memory to a managed object of the specified type. |
PtrToStructure(IntPtr, Object)
Cuidado
PtrToStructure(IntPtr, Object) may be unavailable in future releases. Instead, use PtrToStructure(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296512
Realizar o marshaling de dados de um bloco de memória não gerenciado para um objeto gerenciado.Marshals data from an unmanaged block of memory to a managed object.
public:
static void PtrToStructure(IntPtr ptr, System::Object ^ structure);
[System.Obsolete("PtrToStructure(IntPtr, Object) may be unavailable in future releases. Instead, use PtrToStructure<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296512")]
[System.Security.SecurityCritical]
public static void PtrToStructure (IntPtr ptr, object structure);
public static void PtrToStructure (IntPtr ptr, object structure);
[System.Security.SecurityCritical]
public static void PtrToStructure (IntPtr ptr, object structure);
[System.Runtime.InteropServices.ComVisible(true)]
public static void PtrToStructure (IntPtr ptr, object structure);
[System.Security.SecurityCritical]
[System.Runtime.InteropServices.ComVisible(true)]
public static void PtrToStructure (IntPtr ptr, object structure);
[<System.Obsolete("PtrToStructure(IntPtr, Object) may be unavailable in future releases. Instead, use PtrToStructure<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296512")>]
[<System.Security.SecurityCritical>]
static member PtrToStructure : nativeint * obj -> unit
static member PtrToStructure : nativeint * obj -> unit
[<System.Security.SecurityCritical>]
static member PtrToStructure : nativeint * obj -> unit
[<System.Runtime.InteropServices.ComVisible(true)>]
static member PtrToStructure : nativeint * obj -> unit
[<System.Security.SecurityCritical>]
[<System.Runtime.InteropServices.ComVisible(true)>]
static member PtrToStructure : nativeint * obj -> unit
Public Shared Sub PtrToStructure (ptr As IntPtr, structure As Object)
Parâmetros
- ptr
- IntPtr
Um ponteiro para um bloco não gerenciado de memória.A pointer to an unmanaged block of memory.
- structure
- Object
O objeto para o qual os dados serão copiados.The object to which the data is to be copied. Isso deve ser uma instância de uma classe formatada.This must be an instance of a formatted class.
- Atributos
Exceções
O layout da estrutura não é sequencial nem explícito.Structure layout is not sequential or explicit.
- ou --or-
Estrutura é um tipo de valor demarcado.Structure is a boxed value type.
Comentários
PtrToStructure geralmente é necessário em interoperabilidade COM e invocação de plataforma quando os parâmetros de estrutura são representados como um System.IntPtr valor.PtrToStructure is often necessary in COM interop and platform invoke when structure parameters are represented as an System.IntPtr value. Você não pode usar esse método de sobrecarga com tipos de valor.You cannot use this overload method with value types.
Aplica-se a
PtrToStructure(IntPtr, Type)
Cuidado
PtrToStructure(IntPtr, Type) may be unavailable in future releases. Instead, use PtrToStructure(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296513
Realiza marshal de dados de um bloco não gerenciado de memória para um objeto gerenciado recém-alocado do tipo especificado.Marshals data from an unmanaged block of memory to a newly allocated managed object of the specified type.
public:
static System::Object ^ PtrToStructure(IntPtr ptr, Type ^ structureType);
[System.Obsolete("PtrToStructure(IntPtr, Type) may be unavailable in future releases. Instead, use PtrToStructure<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296513")]
[System.Security.SecurityCritical]
public static object PtrToStructure (IntPtr ptr, Type structureType);
public static object? PtrToStructure (IntPtr ptr, Type structureType);
[System.Security.SecurityCritical]
public static object PtrToStructure (IntPtr ptr, Type structureType);
public static object PtrToStructure (IntPtr ptr, Type structureType);
[System.Runtime.InteropServices.ComVisible(true)]
public static object PtrToStructure (IntPtr ptr, Type structureType);
[System.Security.SecurityCritical]
[System.Runtime.InteropServices.ComVisible(true)]
public static object PtrToStructure (IntPtr ptr, Type structureType);
[<System.Obsolete("PtrToStructure(IntPtr, Type) may be unavailable in future releases. Instead, use PtrToStructure<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296513")>]
[<System.Security.SecurityCritical>]
static member PtrToStructure : nativeint * Type -> obj
static member PtrToStructure : nativeint * Type -> obj
[<System.Security.SecurityCritical>]
static member PtrToStructure : nativeint * Type -> obj
[<System.Runtime.InteropServices.ComVisible(true)>]
static member PtrToStructure : nativeint * Type -> obj
[<System.Security.SecurityCritical>]
[<System.Runtime.InteropServices.ComVisible(true)>]
static member PtrToStructure : nativeint * Type -> obj
Public Shared Function PtrToStructure (ptr As IntPtr, structureType As Type) As Object
Parâmetros
- ptr
- IntPtr
Um ponteiro para um bloco não gerenciado de memória.A pointer to an unmanaged block of memory.
- structureType
- Type
O tipo de objeto a ser criado.The type of object to be created. Esse objeto deve representar uma classe ou estrutura formatada.This object must represent a formatted class or a structure.
Retornos
Um objeto gerenciado que contém os dados apontados pelo parâmetro ptr.A managed object containing the data pointed to by the ptr parameter.
- Atributos
Exceções
O layout do parâmetro structureType não é sequencial ou explícito.The structureType parameter layout is not sequential or explicit.
- ou --or-
O parâmetro structureType é uma definição de tipo genérico.The structureType parameter is a generic type definition.
structureType é null.structureType is null.
A classe especificada por structureType não tem um construtor sem parâmetros acessível.The class specified by structureType does not have an accessible parameterless constructor.
Exemplos
O exemplo a seguir cria uma estrutura gerenciada, transfere-a para a memória não gerenciada e a transfere de volta para a memória gerenciada usando o PtrToStructure método.The following example creates a managed structure, transfers it to unmanaged memory, and then transfers it back to managed memory using the PtrToStructure method.
using System;
using System.Runtime.InteropServices;
public struct Point
{
public int x;
public int y;
}
class Example
{
static void Main()
{
// Create a point struct.
Point p;
p.x = 1;
p.y = 1;
Console.WriteLine("The value of first point is " + p.x + " and " + p.y + ".");
// Initialize unmanged memory to hold the struct.
IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(p));
try
{
// Copy the struct to unmanaged memory.
Marshal.StructureToPtr(p, pnt, false);
// Create another point.
Point anotherP;
// Set this Point to the value of the
// Point in unmanaged memory.
anotherP = (Point)Marshal.PtrToStructure(pnt, typeof(Point));
Console.WriteLine("The value of new point is " + anotherP.x + " and " + anotherP.y + ".");
}
finally
{
// Free the unmanaged memory.
Marshal.FreeHGlobal(pnt);
}
}
}
Imports System.Runtime.InteropServices
Public Structure Point
Public x As Integer
Public y As Integer
End Structure
Module Example
Sub Main()
' Create a point struct.
Dim p As Point
p.x = 1
p.y = 1
Console.WriteLine("The value of first point is " + p.x.ToString + " and " + p.y.ToString + ".")
' Initialize unmanged memory to hold the struct.
Dim pnt As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(p))
Try
' Copy the struct to unmanaged memory.
Marshal.StructureToPtr(p, pnt, False)
' Create another point.
Dim anotherP As Point
' Set this Point to the value of the
' Point in unmanaged memory.
anotherP = CType(Marshal.PtrToStructure(pnt, GetType(Point)), Point)
Console.WriteLine("The value of new point is " + anotherP.x.ToString + " and " + anotherP.y.ToString + ".")
Finally
' Free the unmanaged memory.
Marshal.FreeHGlobal(pnt)
End Try
End Sub
End Module
O exemplo a seguir demonstra como realizar marshaling de um bloco não gerenciado de memória para uma estrutura gerenciada usando o PtrToStructure método.The following example demonstrates how to marshal an unmanaged block of memory to a managed structure using the PtrToStructure method.
Importante
Esse código pressupõe a compilação de 32 bits.This code assumes 32-bit compilation. Antes de usar um compilador de 64 bits, substitua IntPtr.ToInt32 por IntPtr.ToInt64 .Before using a 64-bit compiler, replace IntPtr.ToInt32 with IntPtr.ToInt64.
[StructLayout(LayoutKind::Sequential)]
ref class INNER
{
public:
[MarshalAs(UnmanagedType::ByValTStr,SizeConst=10)]
String^ field;
INNER()
{
field = "Test";
}
};
[StructLayout(LayoutKind::Sequential)]
value struct OUTER
{
public:
[MarshalAs(UnmanagedType::ByValTStr,SizeConst=10)]
String^ field;
[MarshalAs(UnmanagedType::ByValArray,SizeConst=100)]
array<Byte>^ inner;
};
[DllImport("SomeTestDLL.dll")]
static void CallTest(OUTER^ outerStructurePointer);
void static Work()
{
OUTER outerStructure;
array<INNER^>^ innerArray = gcnew array<INNER^>(10);
INNER^ innerStructure = gcnew INNER;
int structSize = Marshal::SizeOf(innerStructure);
int size = innerArray->Length * structSize;
outerStructure.inner = gcnew array<Byte>(size);
try
{
CallTest(outerStructure);
}
catch (SystemException^ ex)
{
Console::WriteLine(ex->Message);
}
IntPtr buffer = Marshal::AllocCoTaskMem(structSize * 10);
Marshal::Copy(outerStructure.inner, 0, buffer, structSize * 10);
int currentOffset = 0;
for (int i = 0; i < 10; i++)
{
innerArray[i] = safe_cast<INNER^>(Marshal::PtrToStructure(
IntPtr(buffer.ToInt32() + currentOffset),
INNER::typeid));
currentOffset += structSize;
}
Console::WriteLine(outerStructure.field);
Marshal::FreeCoTaskMem(buffer);
}
[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);
}
Comentários
PtrToStructure geralmente é necessário em interoperabilidade COM e invocação de plataforma quando os parâmetros de estrutura são representados como um System.IntPtr valor.PtrToStructure is often necessary in COM interop and platform invoke when structure parameters are represented as an System.IntPtr value. Você pode passar um tipo de valor para esse método de sobrecarga.You can pass a value type to this overload method. Nesse caso, o objeto retornado é uma instância do box.In this case, the returned object is a boxed instance.
Confira também
Aplica-se a
PtrToStructure<T>(IntPtr)
[Suporte somente no .NET Framework 4.5.1 e versões posteriores][Supported in the .NET Framework 4.5.1 and later versions]
Realiza marshaling de dados de um bloco não gerenciado de memória para um objeto gerenciado recém-alocado do tipo especificado por um parâmetro de tipo genérico.Marshals data from an unmanaged block of memory to a newly allocated managed object of the type specified by a generic type parameter.
public:
generic <typename T>
static T PtrToStructure(IntPtr ptr);
[System.Security.SecurityCritical]
public static T PtrToStructure<T> (IntPtr ptr);
public static T? PtrToStructure<T> (IntPtr ptr);
public static T PtrToStructure<T> (IntPtr ptr);
[<System.Security.SecurityCritical>]
static member PtrToStructure : nativeint -> 'T
static member PtrToStructure : nativeint -> 'T
Public Shared Function PtrToStructure(Of T) (ptr As IntPtr) As T
Parâmetros de tipo
- T
O tipo do objeto para o qual os dados serão copiados.The type of the object to which the data is to be copied. Isso deve ser uma classe formatada ou uma estrutura.This must be a formatted class or a structure.
Parâmetros
- ptr
- IntPtr
Um ponteiro para um bloco não gerenciado de memória.A pointer to an unmanaged block of memory.
Retornos
- T
Um objeto gerenciado que contém os dados que o parâmetro ptr aponta.A managed object that contains the data that the ptr parameter points to.
- Atributos
Exceções
O layout do T não é sequencial nem explícito.The layout of T is not sequential or explicit.
A classe especificada por T não tem um construtor sem parâmetros acessível.The class specified by T does not have an accessible parameterless constructor.
Comentários
PtrToStructure<T>(IntPtr) geralmente é necessário em interoperabilidade COM e invocação de plataforma quando os parâmetros de estrutura são representados como System.IntPtr valores.PtrToStructure<T>(IntPtr) is often necessary in COM interop and platform invoke when structure parameters are represented as System.IntPtr values. Você pode passar um tipo de valor para essa sobrecarga de método.You can pass a value type to this method overload.
Aplica-se a
PtrToStructure<T>(IntPtr, T)
[Suporte somente no .NET Framework 4.5.1 e versões posteriores][Supported in the .NET Framework 4.5.1 and later versions]
Realiza marshaling de dados de um bloco não gerenciado de memória para um objeto gerenciado do tipo especificado.Marshals data from an unmanaged block of memory to a managed object of the specified type.
public:
generic <typename T>
static void PtrToStructure(IntPtr ptr, T structure);
[System.Security.SecurityCritical]
public static void PtrToStructure<T> (IntPtr ptr, T structure);
public static void PtrToStructure<T> (IntPtr ptr, T structure);
[<System.Security.SecurityCritical>]
static member PtrToStructure : nativeint * 'T -> unit
static member PtrToStructure : nativeint * 'T -> unit
Public Shared Sub PtrToStructure(Of T) (ptr As IntPtr, structure As T)
Parâmetros de tipo
- T
O tipo de structure.The type of structure. Isso deve ser uma classe formatada.This must be a formatted class.
Parâmetros
- ptr
- IntPtr
Um ponteiro para um bloco não gerenciado de memória.A pointer to an unmanaged block of memory.
- structure
- T
O objeto para o qual os dados serão copiados.The object to which the data is to be copied.
- Atributos
Exceções
O layout da estrutura não é sequencial nem explícito.Structure layout is not sequential or explicit.
Comentários
PtrToStructure<T>(IntPtr, T) geralmente é necessário em interoperabilidade COM e invocação de plataforma quando os parâmetros de estrutura são representados como IntPtr valores.PtrToStructure<T>(IntPtr, T) is often necessary in COM interop and platform invoke when structure parameters are represented as IntPtr values. Você não pode usar essa sobrecarga de método com tipos de valor.You cannot use this method overload with value types.