tags:

views:

52

answers:

3

Hi, 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#.

A: 

Please post the signature being used (or else look up pinvoke)

Mitch Wheat
A: 

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.

AdamRalph
+1  A: 

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.

Gregory Pakosz