How can I use unsafe code in VB.Net?

我们两清 提交于 2019-11-26 16:56:33

问题


I would like to know the VB.NET equivalent of the following C# code:

    unsafe
    {
        byte* pStart = (byte*)(void*)writeableBitmap.BackBuffer;
        int nL = writeableBitmap.BackBufferStride;

        for (int r = 0; r < 16; r++)
        {
            for (int g = 0; g < 16; g++)
            {
                for (int b = 0; b < 16; b++)
                {
                    int nX = (g % 4) * 16 + b;                            
                    int nY = r*4 + (int)(g/4);

                    *(pStart + nY*nL + nX*3 + 0) = (byte)(b * 17);
                    *(pStart + nY*nL + nX*3 + 1) = (byte)(g * 17);
                    *(pStart + nY*nL + nX*3 + 2) = (byte)(r * 17);
                 }
            }
        }
   }

回答1:


Looks like it's not possible.

From this post

VB.NET is more restrictive than C# in this respect. It does not permit the use of unsafe code under any circumstances.




回答2:


VB.NET does not allow use unsafe code, but you can do your code in safe managed:

Dim pStart As IntPtr = AddressOf (writeableBitmap.BackBuffer())
Dim nL As Integer = writeableBitmap.BackBufferStride

For r As Integer = 0 To 15
    For g As Integer = 0 To 15
        For b As Integer = 0 To 15
            Dim nX As Integer = (g Mod 4) * 16 + b
            Dim nY As Integer = r * 4 + CInt(g \ 4)

            Marshal.WriteInt32((pStart + nY * nL + nX * 3 + 0),(b * 17))
            Marshal.WriteInt32((pStart + nY * nL + nX * 3 + 1),(g * 17))
            Marshal.WriteInt32((pStart + nY * nL + nX * 3 + 2),(r * 17))
        Next
    Next
Next



回答3:


Not possible, since vb.net does not support unsafe code.




回答4:


You can use this safe code with the same result

Dim pStart As Pointer(Of Byte) = CType(CType(writeableBitmap.BackBuffer, Pointer(Of System.Void)), Pointer(Of Byte))
    Dim nL As Integer = writeableBitmap.BackBufferStride

    For r As Integer = 0 To 15
        For g As Integer = 0 To 15
            For b As Integer = 0 To 15
                Dim nX As Integer = (g Mod 4) * 16 + b
                Dim nY As Integer = r * 4 + CInt(g \ 4)

                (pStart + nY * nL + nX * 3 + 0).Target = CByte(b * 17)
                (pStart + nY * nL + nX * 3 + 1).Target = CByte(g * 17)
                (pStart + nY * nL + nX * 3 + 2).Target = CByte(r * 17)
            Next
        Next
    Next


来源:https://stackoverflow.com/questions/5915874/how-can-i-use-unsafe-code-in-vb-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!