vb.net - Can I have a string object store its data within the structure? -
i'm looking quick way serialize custom structures consisting of basic value types , strings.
using c++cli pin pointer of structure instance , destination array , memcpy data on working quite value types. however, if include reference types such string reference address.
expected since otherwise impossible structure have fixed.. structure. figured maybe, if make string fixed size, might place inside structure though. adding < vbfixedstring(256) > string declaration did not achieve that.
is there else place actual data inside structure?
pinning managed object , memcpy-ing content never give want. managed object, string, character array, or else show reference, , you'll memory location.
if read between lines, sounds need call c or c++ (not c++/cli) code, , pass c struct looks similar this:
struct unmanagedfoo { int a_number; char a_string[256]; }; if that's case, i'd solve setting automatic marshaling handle you. here's how you'd define struct marshals properly. (i'm using c# syntax here, should easy conversion vb.net syntax.)
[structlayout(layoutkind.sequential, charset=charset.ansi)] public struct managedfoo { public int a_number; [marshalas(unmanagedtype.byvaltstr, sizeconst=256)] public string a_string; } explanation:
structlayout(layoutkind.sequential)specifies fields should in declared order. default layoutkind,auto, allows fields re-ordered if compiler wants.charset=charset.ansispecifies type of strings marshal. can specifycharset.ansicharstrings on c++ side, orcharset.unicodewchar_tstrings in c++.marshalas(unmanagedtype.byvaltstr)specifies string inline struct, asking about. there several other string types, different semantics, seeunmanagedtypepage on msdn descriptions.sizeconst=256specifies size of character array. note specifies number of characters (or when doing arrays, number of array elements), not number of bytes.
now, these marshal attributes instruction built-in marshaler in .net, can call directly vb.net code. use it, call marshal.structuretoptr go .net object unmanaged memory, , marshal.ptrtostructure go unmanaged memory .net object. msdn has examples of calling 2 methods, take @ linked pages.
wait, c++/cli? yes, use c++/cli marshal .net object c struct. if structs complex represent marshalas attribute, it's highly appropriate that. in case, here's do: declare .net struct listed above, without marshalas or structlayout. declare c struct, plain , ordinary, listed above. when need switch 1 other, copy things field field, not big memcpy. yes, fields basic types (integers, doubles, etc.) repetitive output.a_number = input.a_number, that's proper way it.
Comments
Post a Comment