Skip to content

Instantly share code, notes, and snippets.

@kimmoli

kimmoli/marshal.cs

Created Feb 3, 2020
Embed
What would you like to do?
/* C++ */
typedef struct {
unsigned long address;
unsigned long length;
unsigned char * data;
} ELEMENT, *PELEMENT;
unsigned long SetElement(ELEMENT Element);
/* C# */
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct Element
{
public unsigned long address;
public unsigned long length;
public IntPtr data;
}
[DllImport("MyDll.DLL", EntryPoint = "SetElement", CharSet = CharSet.Auto)]
public static unsafe extern unsigned long SetElement(Element element);
FileInfo fi = new FileInfo(filename);
Element element = new Element
{
address = startAddress,
length = (unsigned int)fi.Length,
};
element.data = Marshal.AllocHGlobal((unsigned int)fi.Length);
byte[] file = File.ReadAllBytes(filename);
Marshal.Copy(file, 0, element.data, (unsigned int)fi.Length);
SetElement(element);
Marshal.FreeHGlobal(element.data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment