如何在VB.Net中使用不安全的代码?
问题描述:
我想知道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);
}
}
}
}
答
您可以使用pinvoke拨打电话太WinAPI,然后您可以使用不安全的代码。
答
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
答
你可以使用这个安全的代码具有相同的结果
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
虽然已经有很多关于“不是一个真正的问题”的密切投票,我乍一看聚焦问题是“帮助我将这个C#翻译成vb.net”。现在,我不是vb.net专家,但这似乎是一个真正的问题。 – Tesserex 2011-05-06 19:04:56
你可以把它放在一个C#程序集中,并从VB.NET项目中引用它。 – bkaid 2011-05-06 19:07:23
@Bala听起来像是我的答案,但是这个问题*可以*以当前形式合理回答,应该重新打开。 – Justin 2011-05-10 00:57:52