Yet I am writing a wrapper in C++ CLI for our application to give some new parts (written in C#) save and easy access to old native libraries. Therefore I need to pass some structures from C# to C++. These structures are defined in C++ Cli (dotnet) and also in C++.
Example:
\\C+++
typedef struct
{
INFO16 jahr ;
INFO8 monat ;
INFO8 tag ;
INFO8 stunde ;
INFO8 minute ;
}
SDATUM;
\\c++ cli
[StructLayout(LayoutKind::Explicit)]
public value struct SDATUM
{
public:
[FieldOffset(0)]
UInt16 jahr;
[FieldOffset(2)]
Byte monat;
[FieldOffset(3)]
Byte tag;
[FieldOffset(4)]
Byte stunde;
[FieldOffset(5)]
Byte minute;
};
Now I provide some functions in C++ cli which accept this type as dotnet type SDATUM in form of pass by value,by reference (sdatum%) and pointer sdatum* like there corresponding native functions. What do I need to convert/cast these struct?
I found another solution which is very easy, short and does not need copying data. You could call native functions which want a C SDATUM in this way:
//signature
void someFunction(SDATUM datum);
void someFunctionWrapper(SDATUM datum){
pin_ptr<SDATUM> datum_pin=&datum;
//::SDATUM refers to the C-Type
someFunction(*(::SDATUM*)datum_pin);
}
I tested it and it works because both SDATUM Structs have the same bit structure. Because I only call short native functions I think fragmentation is no problem.