Je dois appeler une DLL C++ en C#. Et l'en-tête de la dll est le suivant (simplifié):Comment marshaler un tableau de structure En C#?
// En-tête de C++
struct vector
{
float x;
float y;
vector()
{}
vector(float x0, float y0)
{
x = x0;
y = y0;
}
};
struct unmanaged_struct
{
int int_var;
float float_var;
char* chars_var;
vector vector_var;
unmanaged_struct(int i, float f, char* ch, float vec_x, float vec_y)
{
int_var = i;
float_var = f;
chars_var = ch;
vector_var = vector(vec_x, vec_y);
}
};
// Cette fonction permet de transmettre toutes les valeurs variables de l'instance de struct
extern "C" __declspec(dllexport) void unmanagedstruct_summary(unmanaged_struct* us_list, int length);
Et je définissais la classe suivante en C#
// CSharp
[StructLayout(LayoutKind.Sequential)]
public class Vector
{
public float x;
public float y;
public Vector(float f1, float f2)
{
x = f1;
y = f2;
}
}
[StructLayout(LayoutKind.Sequential)]
public class UnmanagedStruct
{
public int int_var;
public float float_var;
public string char_var;
public Vector vector_var;
public UnmanagedStruct(int i, float f, string s, Vector vec)
{
this.int_var = i;
this.float_var = f;
this.char_var = s;
this.vector_var = vec;
}
}
class UnmanagedDllCallTest
{
[DllImport("unmanageddll.dll", EntryPoint = "unmanagedstruct_summary")]
public static extern void unmanagedstruct_summary([Out]UnmanagedStruct[] usList, int length);
static void Main(string[] args)
{
UnmanagedStruct[] usList = new UnmanagedStruct[1];
usList[0] = new UnmanagedStruct(1, 1.0f, "aa", new Vector(10, 1));
usList[1] = new UnmanagedStruct(2, 2.0f, "ba", new Vector(20, 2));
UnmanagedDllCallTest.unmanagedstruct_summary(usList, 2);
}
Et la sortie est comme suit:
résumé unmanaged_struct:
1.12104e-044
Exception non gérée: System.AccessViolationException: Tentative de lecture ou écriture protégée mémoire. C'est souvent une indication que l'autre mémoire est corrompue. à callunmanageddll.UnmanagedDllCallTest.unmanagedstruct_summary (UnmanagedStr UCT [] usList, longueur Int32) à callunmanageddll.Program.Main (String [] args ) dans c: \ users \ dynaturtle \ docume nts \ studio visuel 2010 \ Projects \ callunmanageddll \ callunmanageddll \ Program.cs: lin e 68
le dll C++ est OK comme je l'ai test écrit en C++ et la fonction fonctionne bien. J'ai lu this thread mais il semble que la solution n'a pas fonctionné dans mon cas. Aucune suggestion? Merci d'avance!
Mais quelle est la différence entre les structures et la classe? –