Skip to content

Porting from C++ with WINAPI

Alex Whitman

Asked Feb 13, 2007, 4:42 AM EST1 answer
Share
LinkedInX

I'm trying to port a c++ class as a way to learn a bit more about c# but some things are bugging me.

If in c++ I have a struct like:

Code

struct MYSTRUCT {
	int id;
	char some_text[FIXED_LENGTH_CONST];
}
what would be the eqivalent in c#? So far I have:
C#

public struct MYSTRUCT {
	public int id;
	[MarshalAs(UnmanagedType.ByValArray, SizeConst=FIXED_LENGTH_CONST)]
	public byte[] some_text
}

Once that is sorted out, how would I go about getting data from a string into some_text so that some_text is ansi c compliant (null terminated). The string needing to go into some_text isn't fixed in size, could be longer or shorter than FIXED_LENGTH_CONST in length. If it is longer then the string should just be copied up to FIXED_LENGTH_CONST.

Next, how do I "pack" the struct into a COPYDATASTRUCT so that it can be sent to another application via SendMessage() and WM_COPYDATA?

I know there are a lot of questions but any help would be great.

Thanks.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Something like this should do the trick:

    [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
    public struct MYSTRUCT {
    public int id;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=FIXED_LENGTH_CONST)]
    public string some_text;
    }

    You can then use some_text as you'd normally use strings within C#. The .NET framework does all the conversion work for you.

    I can't really answer your second question since I have no experience with COPYDATASTRUCT.
    0