Home Ask Login Register

Developers Planet

Your answer is one click away!

user81993 February 2016

Can I have a string object store its data within the structure?

I'm looking for a quick way to serialize custom structures consisting of basic value types and strings.

Using C++CLI to pin the pointer of the structure instance and destination array and then memcpy the data over is working quite well for all the value types. However, if I include any reference types such as string then all I get is the reference address.

Expected as much since otherwise it would be impossible for the structure to have a fixed.. structure. I figured that maybe, if I make the string fixed size, it might place it inside the structure though. Adding < VBFixedString(256) > to the string declaration did not achieve that.

Is there anything else that would place the actual data inside the structure?

Answers


David Yaw February 2016

Pinning a managed object and memcpy-ing the content will never give you what you want. Any managed object, be it String, a character array, or anything else will show up as a reference, and you'll just get a memory location.

If I read between the lines, it sounds like you need to call some C or C++ (not C++/CLI) code, and pass it a C struct that looks similar to this:

struct UnmanagedFoo
{
    int a_number;
    char a_string[256];
};

If that's the case, then I'd solve this by setting up the automatic marshaling to handle this for you. Here's how you'd define that struct so that it marshals properly. (I'm using C# syntax here, but it should be an easy conversion to 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:

Post Status

Asked in February 2016
Viewed 2,564 times
Voted 12
Answered 1 times

Search




Leave an answer


Quote of the day: live life