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

27,448

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).

Share:
27,448
Vikas Kumar
Author by

Vikas Kumar

Updated on December 27, 2020

Comments

  • Vikas Kumar
    Vikas Kumar over 3 years

    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;
    }
    
  • Ben Voigt
    Ben Voigt over 12 years
    If you allocate memory in C++ and return it to C#, you need to later pass the pointer back to C++ to free the memory. The .NET garbage collector can't help you here.