2011-05-06 72 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