How to import const int * const buffer[] into C#? - c#

This is tricky for me.
const int * const buffer[]
Currently, I have it translated as follows:
byte[] buffer
Problem is that I'm getting AccessViolation exceptions, when DLL is calling function with that is using above parameter.
Thanks for help.

With two const's surely that should be indication enough that you're not allowed to change it :-). But, seriously, one of those states that the pointer shouldn't change, the other states that the data pointed to by the pointer shouldn't change.
That's why you're getting the access violation.
What you'll need to do is to copy, not just cast, the data to another buffer which is somewhat less const. Hint: Buffer.BlockCopy is the way to go.

Isn't sizeof(int) > sizeof(byte)? If so, then you will get issues, surely.

The const modifiers do not affect the PInvoke signature, though they may affect how you deal with the data. Since the buffer parameter is an array of pointers to integers the correct translation would be:
IntPtr[] buffer;

Edit: it works now, no AccessViolation exceptions, but I don't know how to retrieve data properly from array like that.
Example file is using this type of access:
buffer[0][i]
buffer[1][i]
but I have only 1 pointer in buffer[]. That pointer is pointer to an 2 dimensional array? How to marshal it then to .NET? Thanks!

Related

C# datatypes in AS3

I'm porting some C# decompression code to AS3, and since it's doing some pretty complex stuff, it's using a range of datatypes such as byte and short. The problem is, AS3 doesn't have those datatypes.
For the most part I can use uint to hold these values. However, at some points, I get a line such as:
length[symbol++] = (short)len;
To my understanding, this means that len must be read and assigned to the length array as a short. So I'm wondering, how would I do this in AS3? I'm guessing perhaps to do:
length[symbol++] = len & 0xFF;
But I'm unsure if this would give a proper result.
So basically, my question is this: how do I make sure to keep the the correct number of bytes when doing this sort of stuff in AS3? Maybe I should use ByteArrays instead?
Depending on reason why cast is in C# code you may or may not need to keep cast in AS3 code. If cast is purely to adjust type to type of elements of length array (i.e. there is no loss of precision) than you don't need cast. If len can actually be bigger than 0x7FFF you'll need to perform some cast.
I think ByteArray maybe a reasonable option if you need to handle result similar to C# StreamReader, random access may be harder than necessary.
Note that short is 2 bytes long (synonym for System.Int16) so to convert to it using bit manipulations you need to do & 0xFFFF. Be also very careful if casting between signed and unsigned types...

Communication between c++ and c# application through network

I have a simple server written in c# listening on some port. I have an application in c++ and I need the application to send some information to the server. This information is a struct containing 5 integers. I was thinking that I can send it also as a string: something like: "ID=3, anotherInt=5...". Is it a good idea? If not, how should I do that?
How to make it work? What is your advice?
Thank you.
I think you have a mistake in your code.
char *ln = "String to send";
connect(client_socket, (struct sockaddr *)&clientService, sizeof(clientService));
send(client_socket,(const char*)&ln, sizeof(ln), 0);
The prototype for send function is:
ssize_t send(int socket, const void *message, size_t length, int flags);
ln is already a pointer to your char buffer. You are passing in &ln, which is the address
of the pointer. Shouldn't it be just "ln"?
You should fix the send() method in client code. sizeof() is wrong way to find the length of string, casts applied on "ln" aren't quite right for what you need there. Check <<this link>> for an example and see how it works for you. BTW, C# code in the server needs some serious re-writing if it were to work predictably. You are using 4096 byte buffer and calls to Read() aren't guaranteed to fetch the entire transmission in one go. You will need a loop just for Read to make sure you are reading everything you need - ofcourse, this needs a clear definition of communication semantics. Happy networking!
First of all, (const char*)&ln is not correct. ln is a char *, so when you take the address of it using & you are getting a char **, which you are then casting to a char *. This is undefined behavior. You'll want to get rid of the & operator. Also you'll probably want to read up on what pointers are and how to use them.
As a rule of thumb, don't cast willy-nilly to make the compiler shut up. The errors are trying to tell you something. However, the sockaddr and sockaddr_in thing is correct; the api is designed that way. If you turn on -Wall in your compiler options, it should give you a warning in the correct place.
ALSO: you want strlen(ln) and not sizeof.
Quick n Dirty Rundown on Pointers
When a type includes * before the variable name, the variable holds a pointer to a value of that type. A pointer is much like a reference in C#, it is a value holding the location of some data. These are commonly passed into functions when a function wants to look at a piece of data that the caller owns, sometimes because it wants to modify it. A string is represented as a char *, which is a pointer to the first character in the string. The two operators that are related to pointers are & and *. & takes an lvalue and returns a pointer to that value. * takes a pointer and returns the value it points to. In this case, you have a string, as a char *, and the function you're calling wants a char *, so you can pass it in directly without casting or using * or &. However, for the other function you have a struct sockaddr_in and it wants a struct sockaddr *, so you (correctly) use & to get a struct sockaddr_in *, then cast it to a struct sockaddr *. This is called "type punning," and is an unpleasant reality of the API. Google will give you a better description of type punning than I can.
connect(client_socket, (struct sockaddr *)&clientService, sizeof(clientService));
this is ok, but this line should read:
send(client_socket,(const char*)ln, strlen(ln), 0);
where the conversion (const char*) can be omitted.
In your code the value of pointer ln is sent (correctly) but you most likely want to send the string it's pointing to in it's entire length.
Concerning the messages to be send: Converting integers to ascii is not a bad idea. You also may have a look at JSON or Googles protobuf format. Formatters or Parsers can easily be written from scratch.

Fixed Size Byte Array

public : array<Byte>^ Foo(array<Byte>^ data)
gets dynamic size managed array
but how can I get fixed size managed byte array?
I wanna force C# user to send me 8 byte array; and get 8 bytes back
style:
public : Byte[8] Foo(Byte[8] data)
EDIT:
can any1 explain why its impossbile in safe context?
C# does not allow you to do that. You'll simply have to validate the array's length and maybe throw an exception if the length is not 8.
Also, the type of your function can't be Byte[8]; you'll have to change that to Byte[].
If you want to force exactly 8 bytes... consider sending a long or ulong instead. Old-school, but it works. It also has the advantage of not needing an object (a byte[] is an object) - it is a pure value-type (a primitive, in this case)
You can use a fixed size buffer inside a struct. You'll need it to be in an unsafe block though.
unsafe struct fixedLengthByteArrayWrapper
{
public fixed byte byteArray[8];
}
On the C++ side you'll need to use inline_array to represent this type.
As Marc correctly says, fixed size buffers are no fun to work with. You'll probably find it more convenient to do runtime length checking.

Scanning byte array as uint array

I have a large byte array with mostly 0's but some values that I need to process. If this was C++ or unsafe C# I would use a 32bit pointer and only if the current 32bit were not 0, I would look at the individual bytes. This enables much faster scanning through the all 0 blocks. Unfortunately this must be safe C# :-)
I could use an uint array instead of a byte array and then manipulate the individual bytes but it makes what I'm doing much more messy than I like. I'm looking for something simpler, like the pointer example (I miss pointers sigh)
Thanks!
If the code must be safe, and you don't want to use a larger type and "shift", them you'll have to iterate each byte.
(edit) If the data is sufficiently sparse, you could use a dictionary to store the non-zero values; then finding the non-zeros is trivial (and enormous by sparse arrays become cheap).
I'd follow what this guy said:
Using SSE in c# is it possible?
Basically, write a little bit of C/C++, possibly using SSE, to implement the scanning part efficiently, and call it from C#.
You can access the characters
string.ToCharArray()
Or you can access the raw byte[]
Text.Encoding.UTF8Encoding.GetBytes(stringvalue)
Ultimately, what I think you'd need here is
MemoryStream stream;
stream.Write(...)
then you will be able to directly hadnle the memory's buffer
There is also UnmanagedMemoryStream but I'm not sure whether it'd use unsafe calls inside
You can use the BitConverter class:
byte[] byteArray = GetByteArray(); // or whatever
for (int i = 0; i < b.Length; I += 2)
{
uint x = BitConverter.ToUInt32(byteArray, i);
// do what you want with x
}
Another option is to create a MemoryStream from the byte array, and then use a BinaryReader to read 32-bit values from it.

Clearing out a c# byte array with sensitive data

I have a c# byte[] containing sensitive data.
What is the best way to clear it?
How do I ensure that something like Array.Clear will not be optimized away?
I cannot think of any circumstance in which a call to Array.Clear would ever be optimized away and even if it could it would only be optimized away in instances where your byte[] was cleared already.
Edit: Something else to consider would be finding out if the framework's SecureString implementation would be useful in your situation:
A SecureString object is similar to a
String object in that it has a text
value. However, the value of a
SecureString object is automatically
encrypted, can be modified until your
application marks it as read-only, and
can be deleted from computer memory by
either your application or the .NET
Framework garbage collector
Even if Array.Clear is guarenteed to be executed (not optimized away) I think you still may have a problem. The GC can move objects around in the heap and there is no guarentee that traces of the original byte will linger if it was moved from one location to another before Array.Clear was called.
You may want to check out SecureString, ProtectedData, or ProtectedMemory. But, if you want a more manual approach I think you are going to have to at least pin the byte array so that the GC cannot move it around. I believe the SecureString uses this trick as well.
A trick that works with most C compilers is to do something like sum all the elements of the cleared array, and then do something with that sum, like print it or xor it with your return value. That way the dead code elimination won't eliminate the clearing of the array.
That said, are you sure that you only need to clear this array? Consider all the other places where the value may also have existed: a buffer in a form, string objects being passed around, key equivalent values in intermediate calculations, or paged out to disk. Zeroizing this one array only gets you 1% of the way there. You have to clear the entire key path.
If you're concerned about Array.Clear, you could always just Marshal.Copy an empty byte array onto the sensitive data.
For example, like this (assuming 'data' is the byte[] containing the sensitive information):
byte[] clear = new byte[data.Length];
unsafe
{
fixed (byte* ptr = &data[0])
{
Marshal.Copy(clear, 0, new IntPtr(ptr), data.Length);
}
}
If you're writing your own encryption routine, my advice would be: don't. You'll get it wrong (as would I, as would anyone who's not a security expert). Use a well-known, tested library.
(If not, never mind!) :)
I was under the impression that there were already techniques to show the recent state of RAM. Then there's also the MIT guys that flash froze some RAM, lifted it and took it somewhere else and maintained all of the state.
So, if you were paranoid, you'd randomly write a whole bunch of data over your array a few times.
AFAIK there is no equivalent to SecureZeroMemory in CLR. You should use SecureString to store your data.

Categories