Passing a Structure to C++ API using Marshal.StructureToPtr in C#

Viewed 24593

I am using API written in C++ in my code (writting in C#). API requires a parameter as Pointer to Structure. The Structure consists of "Int"s and Char Arrays: for example

 unsafe public struct ToBePassed 
    { 
        Int32 Num1;
        Int32 Num2; 
        Char[] Data; // or fixed Char Data[255];
    }

I can not directly pass the structure pointer to API because in that case, I am getting error as "Pointers cannot reference Marshaled structures". Code get compiled successfully but this Error comes when I execute (Debug) the code.

Now I have two options: 1st:- Passing Structure by Ref: I want to ask does an API requiring A Structure Pointer can receive the address when I pass the structure by ref. Note that API will return Data in "Char[] Data".

2nd:- Using Marshal.StructureToPtr: This will convert Structure Pointer to IntPtr. Again the Doubt is same, Will that API receive it correctly?

Thanks for Your Time!

Regards, Swanand

1 Answers
Related