简体   繁体   English

似乎无法从byte []实例变量获取非零的IntPtr

[英]Can't seem to get a non-zero IntPtr from a byte[] instance variable

I've found many ways of getting an IntPtr from a byte[] , all of which I could successfully pass into external unmanaged code, but only if I allocate the byte[] on the stack. 我发现越来越的的许多方面IntPtrbyte[]所有这些我能成功地传递到外部非托管代码,但只有当我分配byte[]在堆栈中。 Attempting to do the same on a byte[] instance variable, I get a null ( IntPtr.Zero ) result, no matter which method of getting an IntPtr I choose. 尝试对byte[]实例变量执行相同的byte[] ,无论选择哪种获取IntPtr方法,我都会得到一个nullIntPtr.Zero )结果。 I haven't found any information on whether or not instance variables are treated differently than those allocated on the stack, in this case. 在这种情况下,我还没有找到关于实例变量是否与堆栈上分配的实例变量区别对待的任何信息。

Here is what I would like to use to acquire a valid IntPtr to a byte[] instance variable: 这是我想用来获取有效的IntPtrbyte[]实例变量的内容:

GCHandle pinned = GCHandle.Alloc(outBytes, GCHandleType.Pinned);
IntPtr ptr = pinned.AddrOfPinnedObject();

// Always true, for reasons I'm unaware.
if (ptr == IntPtr.Zero) {}

pinned.Free();

Thanks! 谢谢!

The only time that GCHandle.Alloc( thing, GCHandleType.Pinned ) results in a handle to IntPtr.Zero is when thing is null. 唯一的一次GCHandle.Alloc( thing, GCHandleType.Pinned )导致手柄IntPtr.Zero是当thing是零。

Your byte array reference is null when you provide it to GCHandle.Alloc() . 将字节数组引用提供给GCHandle.Alloc()时,该引用为null。

Here's where it returns zero: 这是它返回零的地方:

public class ZeroTest
{
    private byte[] someArray;

    public Test()
    {
        this.someArray = null;
    }

    public void DoMarshal()
    {
        GCHandle handle = GCHandle.Alloc( this.someArray, GCHandleType.Pinned );

        try
        {
            // Prints '0'.
            Console.Out.WriteLine( handle.AddrOfPinnedObject().ToString() );
        }
        finally
        {
            handle.Free();
        }
    }
}

Here's where it returns non-zero: 这是返回非零值的地方:

public class Test
{
    private byte[] someArray;

    public Test()
    {
        this.someArray = new byte[1];
    }

    public void DoMarshal()
    {
        GCHandle handle = GCHandle.Alloc( this.someArray, GCHandleType.Pinned );

        try
        {
            // Prints a non-zero address, like '650180924952'.
            Console.Out.WriteLine( handle.AddrOfPinnedObject().ToString() );
        }
        finally
        {
            handle.Free();
        }
    }
}

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

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