1

I have a C# struct that I pass via UDP to a C++ application. I checked the length of a string field and got different results for the C# and C++ codes. Here are the definitions of the structs:

//  C# Side
//-------------
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct stName
{
 /// Some data types
 [MarshalAs(UnmanagedType.ByValTstr, SizeConst = 20)]
 string StringName;
}

// C Side
//---------
struct stName{
/// Some data types
char StringName[20];

When StringName = "192.168.53.2" the size of that field at the C# side is 12 while it is 20 on the C side. What am I doing wrong? If C# uses the actual length of the string, what does the field SizeConst stand for?

1
  • you are passing a TString, you should use LPStr. Commented Jul 13, 2015 at 16:27

1 Answer 1

1

When you check the length of the string in C#, it counts the number of characters (192.168.53.2 is, correctly, 12 characters long).

However, in C, a string is really just an array of characters which is null-terminated. However, the size of the array in this case is just what you set it to, which is 20. So the size of this "field" is 20.

The SizeConst field refers to the size of the C array, so that the interop can create the C array appropriately (with the correct total size).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.