1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
unsafe
{
// Déclaration et initialisation d'une structure
TEST_STRUCT TestStruct;
TestStruct.b_Attribut1 = true;
TestStruct.b_Attribut2 = false;
TestStruct.s_Attribut1 = 1;
TestStruct.i_Attribut1 = 2;
// Déclaration d'un pointeur sur cette structure
TEST_STRUCT* pTestStruct = &TestStruct;
// CAST EN DUR
TEST_STRUCT* pCastEnDur = (TEST_STRUCT*)pTestStruct;
// Récupération du type (que je connais je sais... c'est pour comparer aux test suivant...
System.Type type = pCastEnDur->GetType();
FieldInfo[] fields = type.GetFields();
Console.WriteLine("----------CAST EN DUR------");
Console.WriteLine("Size : " + sizeof(TEST_STRUCT));
Console.WriteLine();
// Affichage des infos en utilisant le type obtenu...
for (int i = 0; i < fields.Length; i++)
{
Console.WriteLine("{0,10}\t:\t{1,20}\t:\t{2,5}", fields[i].Name, fields[i].FieldType.FullName, fields[i].GetValue(TestStruct));
}
Console.WriteLine();
// Et affichage directement par la structure
Console.WriteLine("{0,10}\t:\t{1,20}\t:\t{2,5}", "b_Attribut1", pCastEnDur->b_Attribut1.GetType().FullName, pCastEnDur->b_Attribut1);
Console.WriteLine("{0,10}\t:\t{1,20}\t:\t{2,5}", "b_Attribut2", pCastEnDur->b_Attribut2.GetType().FullName, pCastEnDur->b_Attribut2);
Console.WriteLine("{0,10}\t:\t{1,20}\t:\t{2,5}", "s_Attribut1", pCastEnDur->s_Attribut1.GetType().FullName, pCastEnDur->s_Attribut1);
Console.WriteLine("{0,10}\t:\t{1,20}\t:\t{2,5}", "i_Attribut1", pCastEnDur->i_Attribut1.GetType().FullName, pCastEnDur->i_Attribut1);
Console.WriteLine("----------");
// FIN CAST EN DUR
Console.WriteLine();
Console.WriteLine("----------CAST GENERIQUE------");
// CAST GENERIQUE
// Déclaration d'un IntPtr
IntPtr pPointeur = new IntPtr();
// On copie l'adresse de TestStruct vers cet IntPtr
pPointeur = (IntPtr) pTestStruct;
System.Reflection.Assembly package = Assembly.GetExecutingAssembly();
// On boucle sur toutes les structures de l'Assembly
foreach (System.Type _type in package.GetTypes())
{
// On a trouvé la bonne structure !!! Elle est écrit en dur mais on peut imaginer facilement l'écrire via une String -> générique donc...
if (_type.Name == "TEST_STRUCT")
{
_type.GetFields();
object oTestStruct = Marshal.PtrToStructure(pPointeur, typeof(TEST_STRUCT));
Console.WriteLine("Size : " + Marshal.SizeOf(oTestStruct));
Console.WriteLine();
for (int i = 0; i < fields.Length; i++)
{
Console.WriteLine("{0,10}\t:\t{1,20}\t:\t{2,5}", fields[i].Name, fields[i].FieldType.FullName, fields[i].GetValue(oTestStruct));
}
}
}
// FIN CAST GENERIQUE
} |