Tutorial :changes not reflected in the variable values passed between C# code and C++ code



Question:

I have an application which uses C# front end and a C++ DLL as the backend. I am trying to pass an array from C# code to the C++ code in the DLL which changes the values in that array. But when I try to retrieve the values of the array from C# code after the call is made to the C++ DLL function, the changes are not being reflected. I want the changes to be reflected. Please help me in this regard.

Thanks, Rakesh.


The following are the signatures of the functions that I am using.

In C#:

testStruct(structs, len);  

structs is the array of structures that I am passing.

In C++:

extern "C"  __declspec(dllexport)  void __cdecl  testStruct(structure1*  arrStruct, int len)  

arrStruct is the array of structures which receives the ones passed from C#.


Solution:1

The array is being marshalled by value to the C++ DLL, which means your C++ DLL is working on a copy of the original array. The array needs to be marshalled by reference in order for your C++ code to manipulate the same array which your C# code is referring to.

Rather than investigating methods of marhsalling the array by reference you may want to consider changing your C++ interface so that the manipulated array is returned to your C# code as, for example, a return value.


Solution:2

In your native code:

void fill(int* buffer, size_t length)  {    for (int i = 0; i < length; ++i)      buffer[i] = i;  }  

In your C# code:

[DllImport("Foo")]  static void fill([Out] int[] buffer, UIntPtr length);  

See OutAttribute Class reference.

You can also use [In, Out] if your native method has to the content first before modifying it.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »