views:

822

answers:

1

Hi experts,

I need to process the bytes[] when i get from external application. The external application is also done in c# and they send the bytes thru UDP. They are sending the bytes converted from struct which is stated below :


public struct DISPATCH_MESSAGE
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public char[] federation_name; // Units: nil     Range: nil
}


So, when i get the bytes, i need to take out the char[] inside that, and get the string out of that char[].

I hope my explanation is clear. i am new to this kind of unmanaged coding. Please help me on this. Its urgent. Thanks.

+1  A: 

Probably you should declare it as ByValTStr (depending on the nature of the string, it might be different):

 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
 public struct DISPATCH_MESSAGE{ 
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]   
    public string federation_name; 
 }

UPDATE: If it's already giving out a char[], it's probably doing the necessary conversion (includes handling encoding) correctly, so I think you'd just need:

string str = new string(instance.federation_name);
Mehrdad Afshari
I dont have the access to the external application. Anything i have to do, shud be in my application.thanks.
Anuya
hi, how do i get the instance in string str = new string(instance.federation_name); ???Thanks. I am a new bie to this.
Anuya
There is probably a function that returns (or takes) such an instance... Isn't there? If not, what's the point in using that struct?
Mehrdad Afshari
yeah that is fine...So do u mean than, the unmanaged char[] dosent matter for getting the string from that is it ?As far as i googled, i got to know that we have to use Marshall to do it.Correct me if i am wrong. Thanks.
Anuya
@karthik: You said you can't alter the definition of the struct in your code as it's in a separate library. If you haven't declared DISPATCH_MESSAGE (the managed one) in your code, probably the library that declares it has some methods that return an instance. If not, then you *do have control* on the managed definition of the struct and in that case, you need to know the format (is it null terminated, is it unicode, ...) of the string stored in unmanaged char[] to take that out correctly.
Mehrdad Afshari
Okay..I will first know the format of string stored in unmanaged char[]. I will revert u back as soon as poss. Thnx a lot.
Anuya
i found out the problem. i have to remove the header from bytes before processing body.This worked out.
Anuya