pinvoke - How to marshal an array of structure In C#? -
i have call c++ dll in c#. , header of dll following(simplified):
//header of 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); } };
// function used output variable values of struct instance
extern "c" __declspec( dllexport ) void unmanagedstruct_summary(unmanaged_struct* us_list, int length);
and defined following class in 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); }
and output following:
unmanaged_struct summary:
0
1.12104e-044
unhandled exception: system.accessviolationexception: attempted read or write protected memory. indication other memory corrupt. @ callunmanageddll.unmanageddllcalltest.unmanagedstruct_summary(unmanagedstr uct[] uslist, int32 length) @ callunmanageddll.program.main(string[] args) in c:\users\dynaturtle\docume nts\visual studio 2010\projects\callunmanageddll\callunmanageddll\program.cs:lin e 68
the c++ dll ok have written test in c++ , function works well. have read this thread seems solution didn't work in case. suggestions? in advance!
use marshal.ptrtostructure
. there sample here.
so have change signature of method out structure array out intptr. however, need know size of buffer being passed out.
public struct vector { public float x; public float y; } public struct unmanagedstruct { public int int_var; public float float_var; public string char_var; public vector vector_var; } class unmanageddllcalltest { [dllimport("unmanageddll.dll", entrypoint = "unmanagedstruct_summary")] public static extern void unmanagedstruct_summary([out] intptr ptr, int length); static void main(string[] args) { for(int i=0; i<length; i++) { unmanagedstruc st; marshal.ptrtostructure(ptr, st); // increment ptr , move forward } }
Comments
Post a Comment