passing string without '\0' termination

  • Thread starter Thread starter GB
  • Start date Start date
G

GB

Hi,

I have a structure which I want to pass as a pointer to a C dll. The
problem is that C# adds '\0' character at the end of each string
(which is contained in the struct).

I understand that C# does it so that no null terminated strings are
passed but I want to pass the strings without the padding.

Example,

[StructLayout(LayoutKind.Sequential)]
public struct Name
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst= 6)]
public string LastName
};

Name nm = new Name();
nm.Lastname = "GEORGE";

Cfunction(ref nm); //here at the 'C' end the value of LastName becomes
// LastName[0] = 'G'
// LastName[1] = 'E'
// LastName[2] = 'O'
// LastName[3] = 'R'
// LastName[4] = 'G'
// LastName[5] = 0
Instead of '0' I want 'E' (basically no '\0' termination)

Is there any other way except increasing the size of LastName(which
would increase the size of struct)?

Thanks a lot,
Gaurav
**************************
 
Hi,
inline

GB said:
Hi,

I have a structure which I want to pass as a pointer to a C dll. The
problem is that C# adds '\0' character at the end of each string
(which is contained in the struct).

I understand that C# does it so that no null terminated strings are
passed but I want to pass the strings without the padding.

Example,

[StructLayout(LayoutKind.Sequential)]
public struct Name
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst= 6)]
public string LastName
};

One way is to declare LastName as a character array:
[MarshalAs(UnmanagedType.ByValArray, SizeConst=6)]
public char[] LastName;
Name nm = new Name();
nm.Lastname = "GEORGE";

would become:
nm.Lastname = "GEORGE".ToCharArray(0,6);

hth,
greetings

Cfunction(ref nm); //here at the 'C' end the value of LastName becomes
// LastName[0] = 'G'
// LastName[1] = 'E'
// LastName[2] = 'O'
// LastName[3] = 'R'
// LastName[4] = 'G'
// LastName[5] = 0
Instead of '0' I want 'E' (basically no '\0' termination)

Is there any other way except increasing the size of LastName(which
would increase the size of struct)?

Thanks a lot,
Gaurav
**************************
 
Back
Top