2011-05-06 42 views
6

我想知道VB.NET相当于下面的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); 
       } 
      } 
     } 
    } 
+1

虽然已经有很多关于“不是一个真正的问题”的密切投票,我乍一看聚焦问题是“帮助我将这个C#翻译成vb.net”。现在,我不是vb.net专家,但这似乎是一个真正的问题。 – Tesserex 2011-05-06 19:04:56

+3

你可以把它放在一个C#程序集中,并从VB.NET项目中引用它。 – bkaid 2011-05-06 19:07:23

+0

@Bala听起来像是我的答案,但是这个问题*可以*以当前形式合理回答,应该重新打开。 – Justin 2011-05-10 00:57:52

回答

7

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

+9

您不应通过复制他人的答案来回答自己的问题。只需接受巴拉R的回答。 – sfarbota 2015-10-13 20:04:08

16

看起来这是不可能的。

this post

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

0

您可以使用pinvoke拨打电话太WinAPI,然后您可以使用不安全的代码。

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 
+1

这是不一样的。不安全的代码允许使用指针,这个托管代码使用引用。引用比指针慢得多。 – Nick 2014-05-14 13:22:10

+0

谁在乎0.00001sec和0.00002sec? – Minh 2014-05-15 13:46:34

+0

使用指针不仅仅是使用引用的一半时间。 – Nick 2014-05-15 20:16:00

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 
+2

'Pointer'是'System.Reflection.Pointer'类吗?这是我能找到的唯一一个,但它看起来不正确(它需要使用.Box和.Unbox静态方法来保护/取消保护不安全的内存)... – 2014-10-02 14:34:33