views:

1064

answers:

4

I have an unmanaged C dll I call from a C# class library that encrypts a string value into an encrypted string that contains non-ascii characters. I need to take the data and write its binary values to a file but C# treats text as strings rather than a byte[]. The encrypted value commonly contains special characters (\r, \O, etc). When I do this converting the returned string to C# using some type of codeset (ascii, utf-7, utf-16) it writes the special character values as the windows interpreted values instead their actual binary representation.

My question is how can I pull the data from the unmanaged dll into a byte[] rather than a string so I can write that to file using the BinaryWriter?

Thanks.

+1  A: 

If I understand you correctly, I think you want Encoding.GetBytes() probably with UTF8?

tvanfosson
A: 

I have tried that but for the characters that are not ascii it uses two bytes instead of the expected one. I need a one-to-one conversion of characters to bytes.

+1  A: 

Have you tried using the ASCIIEncoding class? It should turn any UTF-8 characters into the ascii character for '?'

MSDN Page

Usage

ASCIIEncoding ascii = new ASCIIEncoding();
Byte[] encodedBytes = ascii.GetBytes(unicodeString);
Stephen Edmonds
A: 

Are you using P/Invoke? Hmm... Perhaps the specifying [MarshalAs(UnmanagedType.*)] would help. Also, you could create an intermediary C function that instead exposes the encrypted data as (void *). That should be easier to get into a byte[].

David Grant