Creating a basic C++ .dll for p/invoke in C#

后端 未结 1 1097
小鲜肉
小鲜肉 2021-01-06 05:41

I am a C# programmer, and unfortunately due to both age and experience, I did not have the luxury of getting the chance to go through the C++ era of programming in my learni

相关标签:
1条回答
  • 2021-01-06 06:08

    The third parameter needs to be a byte[], marshalled as a char*, of size 16.

    If you check the documentation for ReadProcessMemory, it takes a buffer and a size, and this function passes the size as 16 bytes. This means that you will need a 16-byte array. The runtime should be perfectly happy to marshal a byte[] of size 16. Be careful not to mix C++ char with C# char- the C# char is actually a C++ wchar_t on Windows. The C++ char is C#'s byte.

    Not that I have any actual idea about how that functions works- I just traced the usage of the third parameter and it only actually gets passed to ReadProcessMemory, the parameters for which are quite clearly documented.

    To package into a .dll (assuming you have nothing else to go into that .dll), you want to add a couple things on to the beginning to ask the C++ compiler not to mangle the name and to export it for you, producing this as the first line

    extern "C" __declspec(dllexport) void GetListItemData( HWND hListWnd, long index, char *outputResult )
    

    You'll only need one C++ source file, no headers, and compile as DLL (it's in the project settings). You won't need any code except the function and any includes that you need.

    In C#

    [System.Runtime.InteropServices.DllImport(
        DLLPath,
        CallingConvention = CallingConvention.Cdecl
    )]
    private static extern void GetListItemData(
        System.IntPtr hWnd,
        System.Int32 index,
        [MarshalAs(UnmanagedType.LPArray)]byte[] buffer
    );
    

    Unfortunately, it's up to you to make sure that buffer is of sufficient size.

    0 讨论(0)
提交回复
热议问题