user3530012
user3530012

Reputation: 740

Convert c++ char array to c# string

I have a struct in C++ which has a char[10] field.

struct Package
{
    char str[10];
};

I convert the struct into char array and send it to and c# application over a TCP socket and there I convert it back to a c# struct.

[StructLayout(LayoutKind.Sequential)]
public struct Package
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
    public string str;
};

The convertion is done properly and I get the message but the problem is when the length of the message is less than the size of the array and I think that it's due to the null terminator in c++ char array.

For instance if the I send "Hello\0" from C++ the char array is something like:

H e l l o \0 \0 \0 \0 \0

And when I get it in c# application it is something like:

H e l l o Ì Ì Ì Ì Ì

And I really don't know what to do with this (personally like to call) junk character 'Ì'.

please help me on this. Any help is appreciated.

Update:

I simply cast the struct to char* and send it over the socket;

Package pkg;
strcpy_s(pkg.str, 'Hello\0');

char* bytes = (char*)&pkg;

send(socket, bytes, sizeof(pkg), NULL);

Upvotes: 2

Views: 4806

Answers (3)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

I don't know any C#, but may be you can solve the problem this way

Package pkg;
strcpy_s(pkg.str, 10, "Hello");

char* bytes = (char*)&pkg;

send(socket, bytes, sizeof(pkg), NULL);

The strcpy_s function takes the size of the dst buffer as an argument to avoid an overflow (see here). I asked in the comments about the way you inovke it, because it doesn't even look like it's valid C++.

The terminating null byte is added to pkg.str automatically and also "Hello" has a terminating null byte after the o character, and you don't have to add it manually.

I assumed that C# knows how to handle the recieved string, so if you send the right string, it should be recived correctly.

Upvotes: 4

LPs
LPs

Reputation: 16223

You are sending sizeof array instead of strlen of str.

Take notes that if you send with strlen you need to add 1 to send the null termination of string

Upvotes: 2

LPs
LPs

Reputation: 16223

This is what I usually do in my wrappers dll with serial line

        public byte[] RXArray = new byte[length];

        byte[] appo = new byte[MsgLength];
        Array.ConstrainedCopy(RXArray, NcharsToCopy, appo, 0, MsgLength);
        string ConvertedToString = System.Text.Encoding.UTF8.GetString(appo);

Upvotes: 1

Related Questions