开发者

Passing an array by reference in C# and managed C++

here is the situation: I want to call a method from a C++ module, and pass an array to it:

x.Method(array, ...)

x is a C# object. I would suppose that I could change the array and fill it with my o开发者_StackOverflow社区wn data - but it seems not be the case (?)

How should I pass the array by reference and change its content in the method?

Thank you in advance,

cheers.


Yes, if you want to alter the array beyond just altering its elements (i.e. adding or removing elements) then you have to pass it by reference. The C# declaration would be:

 public void Method(ref Mumble[] arg)

Which isn't great syntax. The garbage collector makes it easy to return an array as the function return value:

 public Mumble[] Method(Mumble[] input)

But consider a List<Mumble> instead.


You don't need to pass the array by reference. Array is a reference type, so if you pass the array to the method, you're actually passing a reference to it. The method can change the content of the array pointed by the reference, but cannot change the reference itself (i.e. it can't make it point to a different array). If you were passing the array by reference, the method would be able to change the reference to the array, but that's probably not what you're looking for if you just want to fill an existing array.

I suggest you have a look at this article for more details

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜