繁体   English   中英

带有void *的PInvoke与带有IntPtr的结构

[英]PInvoke with a void * versus a struct with an IntPtr

想象一下,我有一个叫做的函数

Myfunction(const void * x);

我的C#声明可能是

MyFunction(IntPtr x);

这在功能和技术上是等同于

struct MyStruct { IntPtr P; }

MyFunction(MyStruct x);

或者他们的编组方式会有所不同。

我问这个是因为我正在调用的库是无效的*,对其他名称键入了类型,而在C#中我希望获得类型安全性,因为它的价值。

如果您的StructLayout是Sequential,那么它确实是相同的。

最简单的方法是自己验证这个,当然是尝试一下:

制作一个C ++ Win32 DLL项目:

extern "C"
{
    __declspec(dllexport) void MyFunction(const void* ptr)
    {
       // put a breakpoint and inspect
    }
}

制作一个C#项目:

    public struct Foo
    {
        public IntPtr x;
    }

    [DllImport(@"Win32Project1.dll", EntryPoint = "MyFunction", CallingConvention = CallingConvention.Cdecl)]
    public static extern void MyFunctionWithIntPtr(IntPtr x);

    [DllImport(@"Win32Project1.dll", EntryPoint = "MyFunction", CallingConvention = CallingConvention.Cdecl)]
    public static extern void MyFunctionWithStruct(Foo x);

    static void Main(string[] args)
    {
        IntPtr j = new IntPtr(10);
        var s = new Foo();
        s.x = new IntPtr(10);
        MyFunctionWithIntPtr(j);
        MyFunctionWithStruct(s);
    }

在调试设置中,确保选择“启用本机调试”。

你会看到两个值都是0xA。

但是,请注意,如果对IntPtr vs Struct使用out / ref参数,它们将是不同的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM