Vikas Kumar
Vikas Kumar

Reputation: 231

How to pass C# array to C++ and return it back to C# with additional items?

I have a C# project which is using a C++ dll. (in visual studio 2010)

I have to pass a array of int from C# code to C++ function and C++ function will add few elements in array, when control comes back to C# code, C# code will also add elements in same array.

Initially i declared a array(of size 10000) in C# code and C++ code is able to add elements (because it was just an array of int, memory allocation is same), but the problems is i have got run time error due to accessing out side of array.

I can increase size to 100000 but again i don't know how much elements C++ code will add( even it can be just 1 element).

So is there a common data structure (dynamic array) exist for both or other way to do? I am using Visual studio 2010.

Something like this i want to do.
PS: not compiled code, and here i used char array instead of int array.

C# code

[DllImport("example1.dll")]
private static extern int fnCPP (StringBuilder a,int size)
...

private void fnCSHARP(){
    StringBuilder buff = new StringBuilder(10000);
    int size=0;
    size = fnCPP (buff,size);
    int x = someCSHARP_fu();
    for ( int i=size; i < x+size; i++) buff[i]='x';// possibility of run time error
}

C++ code

int fnCPP (char *a,int size){
  int x = someOtherCpp_Function();
  for( int i=size; i < x+size ; i++) a[ i ] = 'x'; //possibility of run time error 
  return size+x;
}

Upvotes: 13

Views: 30883

Answers (1)

Amittai Shapira
Amittai Shapira

Reputation: 3827

There's a good MSDN article about passing arrays between managed and unmanaged code Here. The question is, why would you need to pass the array from C# to C++ in the first place? Why can't you do the allocation on the C++ side (in your fnCPP method), and return a pointer to the C# code, and than just use Marshal.Copy( source, destination, 0, size ) as in yet another Stackoverflow question? Than in your fnCSHARP method you could copy the contents of the array to some varaiable length data structure (e.g. List).

Upvotes: 8

Related Questions