Correct way to marshal SIZE_T*?

前端 未结 2 1286
挽巷
挽巷 2020-12-30 02:23

I have the following C++ function definition, which I am trying to call through PInvoke from managed code:

bool FooBar(SIZE_T* arg1);

My ma

相关标签:
2条回答
  • 2020-12-30 03:07

    UIntPtr is the correct type to use.

    size_t is an unsigned, pointer-sized integer and that's exactly what UIntPtr means. The "ptr" in the name can be a bit confusing, I agree. It doesn't actually mean "this is a pointer", it means "this is a pointer-sized integer". So your declaration would be:

    [DllImport("mydll", SetLastError=true, CharSet=CharSet.Unicode)]
    private static extern bool FooBar(ref UIntPtr arg1);
    
    0 讨论(0)
  • 2020-12-30 03:15

    Using IntPtr and/or UIntPtr is doing it properly - the types are there specifically for this purpose! I do not understand why you consider it an "ugly hack". I'm also not sure what your proposed alternative would be - any kind of attribute to allow values to be mapped to uint would be inherently wrong, because C# uint is guaranteed to be 32-bit regardless of the architecture, and so on 64-bit platform, to marshal it correctly, it would have to trim half of it, losing data, and likely rendering the result useless.

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