SoFunction
Updated on 2025-03-02

C# accesses array pointers dynamically allocated by C++ (example explanation)

When C# calls the C++ algorithm library in the project, the C++ internal operation results return a rectangular coordinate array (the previous length is unknown and unpredictable). The following method is suitable for accessing any structure type array allocated internally by C++. At that time, I took it for granted that the parameters were passed using ref array[], which could calculate and allocate, but in C#, I only got the arr length of 1, and I could not access the subsequent array Item.

C++

Interface example:

void Call(int *count, Rect **arr)
{
 //…..
 //Re-machine a piece of memory, copy the pointer to the parameter, the length is not known before the external call, and also provides interface Free memory. //….
}

Structure:

Struct Rect
{
int x;
int y;
int width;
int height;
};

C#:

Structure:

Struct Rect
{
public int x;
public int y;
public int width;
public int height;
}

External DLL method declaration:

 [DllImport("", EntryPoint = "Call", CallingConvention = , ExactSpelling = true)]
 public static extern void Call(
     ref int count,
     ref IntPtr pArray);

Method call:

IntPtr pArray = ; //Array pointerint count = 0;
Call(ref count, ref pArray);
var rects = new Rect[count]; //Result arrayfor (int i = 0; i < count; i++)
{
var itemptr = (IntPtr)((Int64)Rect + i * (typeof(Rect))); //The UInt32 is used here, and it overflowed when I used it, and it was replaced with Int64rects[i] = (Rect)(itemptr, typeof(Rect));
}

Reference link:Detailed explanation of the problem of calling c++Dll structure array pointer based on C#

The above article C# access C++ dynamically allocated array pointers (example explanation) is all the content I share with you. I hope you can give you a reference and I hope you can support me more.