如何在VB.Net中使用不安全的代码?

时间:2011-05-06 19:01:23

标签: c# vb.net unsafe

我想知道以下C#代码的VB.NET等价物:

    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);
                 }
            }
        }
   }

4 个答案:

答案 0 :(得分:20)

看起来不可能。

来自this post

  

VB.NET比C#更具限制性   这方面。它不允许   在任何情况下使用不安全的代码   情况。

答案 1 :(得分:5)

不可能,因为vb.net不支持不安全的代码。

答案 2 :(得分:5)

VB.NET不允许使用不安全的代码,但您可以安全管理代码:

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 :(得分:3)

您可以使用具有相同结果的此安全代码

 
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