How do you pass a int pointer to a function with parameter of type int [] ? I need to pass the pointer data from below code:
char* data = stackalloc char[123];
to a function with parameter of int [].
foo(char [])
Follow up question:
How is the int[] represented in C# ? Is it the same as in C++ (pointer ?)
Don't use unsafe code unless you have a good reason.
In any case, you can only use and manipulate pointers in unsafe code. Your Foo method accepts int[], not int*, not char*, not void*. int[] is safe and verifiable - char* isn't. You simply cannot pass a pointer, much less a pointer that's of a different type.
I assume you're just confused about how C# works, and you're trying to write C code in C#. If you want to work with an integer array, work with an integer array. If you want to work with a char array, use a char array.
Arrays are an actual type in C#, unlike C's syntactic sugar - this means they're a lot easier to work with, but it also means that they behave very differently from C. The same way, you shouldn't really use stackalloc unless it's necessary - leave the memory management to the runtime, 99% of the time. Only think about hacks like this when you've identified this code as the bottleneck, and even then only if the performance improvements (if any) are worth it.
So yes, working with arrays is as simple as this in C#:
var integerArray = new int[] { 1, 2, 3 };
var charArray = new char[] { 'a', 'b', 'c' };
MethodTakingIntArray(integerArray);
MethodTakingCharArray(charArray);
If you need stackalloc (again, you really shouldn't, most of the time), all the methods handling that pointer must be unsafe, and they must take a pointer argument:
private unsafe void HandleArray(int* array)
{
// Do whatever
}
The reason is simple - unsafe code isn't verifiable by the runtime, and pointers aren't arrays. While you can do integerArray.Length, there's no such thing on a pointer (obviously) - they're a completely different type.
Another warning: char isn't the same thing as in C/C++. If you want a byte array, use byte[] - char is actually a unicode character, and shouldn't be used for non-character data.
Read this : https://msdn.microsoft.com/en-us/library/4d43ts61(v=vs.90).aspx
Since arrays are reference type, when you pass an array to a function, you pass a reference(or a pointer) to the array.
You would pass it simply like this:
int[] arr = {1, 2, 3};
foo(arr);
And this is how you create a char array in C#:
char[] data = new char[123];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With