|
|
От: |
Serginio1
|
https://habrahabr.ru/users/serginio1/topics/ |
| Дата: | 26.03.19 15:59 | ||
| Оценка: | |||
private IntPtr MarshalToPointer(
object data)
{
IntPtr buf = Marshal.AllocHGlobal(
Marshal.SizeOf(data));
Marshal.StructureToPtr(data,
buf, false);
return buf;
}This simply returns an IntPtr to an area of the global heap that contains a copy of the data. The only problem with this function is that you have to remember to release the allocated heap memory after use. For example:
IntPtr lpstruct =
MarshalToPointer(Sinfo);
result = AVIFileCreateStream(pFile,
ref pStream, lpstruct);
Marshal.FreeHGlobal(lpstruct);…works exactly like default marshalling. But don’t forget that lpstruct is itself still being marshalled as a pass-by-value integer. To copy the result back to the struct an additional function is required:
private object MarshalToStruct(
IntPtr buf,Type t)
{
return Marshal.PtrToStructure(
buf, t);