5

How to redo the declaration of that C++ template function in C#?

    template <class type>
void ReadArray(type * array, unsigned short count)
{
    int s = sizeof(type) * count;
    if(index + s > size)
        throw(std::exception("Error 102"));
    memcpy(array, stream + index, s);
    index += s;
}   

When called,it append bytes/word/(type) in the given array by reading a stream(stream) at a specific position(index).

I tried to redo the declaration like this,but i get an error

    public static T void ReadArray(<T> Array inputarray) // error
    {
        ...
    }

Thanks!

Another conservative question - how to append the bytes into that array(memcpy()),should i use a pointer?

2 Answers 2

16

You use it like this:

public static void ReadArray<T>(T[] inputArray) {
   ...
}

You can use the Array.Copy method to copy data between arrays.

Edit:
If you want to make a "blind copy" of data between different data types, e.g. byte array to long array, that's not something that you can do using safe code. You can use the BitConverter class for example to convert eight bytes from an array into a long. You could also use unsafe code with pointers to do the "blind copy", but you should save that until you actually run into performance problems using safe methods.

Sign up to request clarification or add additional context in comments.

Comments

2
public static void ReadArray<T>(T[] inputarray)
    {
        ...
    }

To append to an array you should covert it to a List

List<T> list = new List<T>();
list.AddRange(inputarray);
list.AddRange(anotherArray);

3 Comments

Woops, thanks for correcting me mate, I just copy and pasted without checking
I dont understand the copy method.What is the another array - is it the stream in the C++ code?
Sorry after reading your code again I think what you really need is copy not append. Just use Array.Copy() as suggested by Guffa.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.