miercuri, 14 august 2013

Passing structures to C++ using C#

An ever reoccurring problem for developers having to integrate legacy C++ libraries with .NET Framework projects is passing structures to the C++ layer and getting back the results.
I have searched the web and I have found a few threads looking into this problem as well as the official MSDN documentation.

http://stackoverflow.com/questions/3939867/passing-a-structure-to-c-api-using-marshal-structuretoptr-in-c-sharp
http://objectmix.com/dotnet/796796-ptrtostructure-failing-structure-must-not-value-class.html
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.structuretoptr.aspx

For my own needs, I am using the following code snippet, that is used to pass a structure by reference to a C++ function and get back the structure filled with the data.

In the code below, the StructureToPass structure must match the definition of the equivalent C++ structure and must be decorated with the StructLayout(LayoutKind.Sequential) attribute.

[StructLayout(LayoutKind.Sequential)]
public struct StructureToPass  
{
        public uint x;       
        public float y;
        public float z;
}

StructureToPass tsData = new StructureToPass();
IntPtr strPtr = Marshal.AllocHGlobal(Marshal.SizeOf(tsData));

try
{ 

    Marshal.StructureToPtr(tsData, strPtr, false);

    if ( 0 == GetStructureFromCPP(strPtr))
    {
       
tsData = (StructureToPass)Marshal.PtrToStructure(strPtr, typeof(StructureToPass));

    }
}
}
catch (Exception ex)
{
}
finally
{
   
Marshal.FreeHGlobal(strPtr);
}
 

Niciun comentariu:

Trimiteți un comentariu