Answers for "Marshall arrays of struct in C#"

C#
0

Marshall arrays of struct in C#

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct TheTypeOfYourFunction
{
  	int parameter1;
  	int parameter2;
}


[DllImport("yourdll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
//EVERY C/C++ ARRAY COMES WITH ITS SIZE PARAMETER. You need to get the size of the returning 
//array in order to instanciate one in your C# code. The size parameter is  often passed by reference 
//by the C/C++ dll, and this is the way to recover it.
static extern IntPtr TheFunctionThatReturnsAnArrayOfStructures(int out size);

public void ImUsingMyExternFunctionHere(){
	int size;
    //You get the size by passing the parametter by adress using the keword "out" in the declaration 
  //and the definition of the method.
	intPtr pointer =  TheFunctionThatReturnsAnArrayOfStructures(out size);    
    TheTypeOfYourFunction[] myFinalArrayOfStructures = new TheTypeOfYourFunction[size] 
        //you add one by one everyparameter to your newly created array
    IntPtr loopPointer = pointer;
	//the sizeof function has to be used in an unsafe context if you want your
  //code to compile
    unsafe{
    	for (int i = 0; i<myFinalArrayOfStructures.Lenght;i++){
    		myFinalArrayOfStructures[i]=Marshal.PtrToStructure<TheTypeOfYourFunction>(loopPointer);
        	loopPointer = IntPtr.Add(loopPointer ,sizeof(TheTypeOfYourFunction));//before thet line, the pointer pointed the first index of your array. by doing this, you make your pointer point to the next address.
    	}
    }    
  	// and there you go, your array of structure is in the myFinalArrayOfStructures variable.
  //REMEMBER : 
  //if it's a structure, use Marshal.PtrToStructure<T>(). 
  //If it's an array, use a IntPtr and loop into it using IntPtr.Add()
}
Posted by: Guest on August-17-2021

C# Answers by Framework

Browse Popular Code Answers by Language