Skip to content

Instantly share code, notes, and snippets.

@Ch3shireDev
Last active June 15, 2022 08:02
Show Gist options
  • Select an option

  • Save Ch3shireDev/a48accb8b7c7817d3a6c8bafd8d29711 to your computer and use it in GitHub Desktop.

Select an option

Save Ch3shireDev/a48accb8b7c7817d3a6c8bafd8d29711 to your computer and use it in GitHub Desktop.
C# C++ interop structs
    // code in C#
    [StructLayout(LayoutKind.Sequential)]
    public struct Point
    {
        [MarshalAs(UnmanagedType.I4)]
        public int x;
        [MarshalAs(UnmanagedType.LPStr)]
        public string y;
    }

    public static class DllExports
    {
        [DllExport]
        public static void Test(ref Point x)
        {
            MessageBox.Show($"Data: {JsonConvert.SerializeObject(x)}");
        }
    }
    // code in C++
    
    struct X{
        int x;
        const char* y;
    };

    int main()
    {
        HWND lib = LoadLibrary("library.dll");
        HWND f_addr = GetProcAddress(lib, "Test");
        void(*Test)(X*) = reinterpret_cast<void(*)(X*)>(f_addr);
        X *x = new X();
        x->x = 5;
        x->y = "abc";
        Test(x);
        // result:
        // Data: {"x":5,"y":"abc"}
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment