13

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;
}
3
  • 2
    Can you use C++/CLI?Can you use C++/CLI? Commented Oct 2, 2011 at 7:06
  • 2
    You can't "add" items to an array. Arrays are fixed in size. Use a different data structure or change how you interface between the two. Commented Oct 2, 2011 at 8:42
  • @Jeff that was not exactly "add", i have added code to clear from my side Commented Oct 2, 2011 at 9:43

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.