VB.Net中不安全

时间:2012-12-20 00:42:20

标签: c# vb.net bitmap unsafe

我需要将函数C#传递给VB.NET,但在C#中我有类似的东西:

unsafe
{
    byte* pSmall = (byte*)(void*)smallData.Scan0;
    byte* pBig = (byte*)(void*)bigData.Scan0;

    int smallOffset = smallStride - smallBmp.Width * 3;
    int bigOffset = bigStride - bigBmp.Width * 3;

    bool matchFound = true;
    ....
}

我在一些博客中读到VB.Net中不存在“不安全”。问题是:我可以使用什么代替unsafe

2 个答案:

答案 0 :(得分:4)

你读过的博客是正确的,因为没有办法在VB.NET中使用不安全的代码。看起来你想操纵位图文件(可能读取像素数据?)。在C#中,您可以使用不安全的代码来提高GetPixel方法的性能。在VB.NET中,您可以尝试查看LockBits

this page上有一个如何使用它的例子。

 
Public g_RowSizeBytes As Integer
Public g_PixBytes() As Byte

Private m_BitmapData As BitmapData

' Lock the bitmap's data.
Public Sub LockBitmap(ByVal bm As Bitmap)
    ' Lock the bitmap data.
    Dim bounds As Rectangle = New Rectangle( _
        0, 0, bm.Width, bm.Height)
    m_BitmapData = bm.LockBits(bounds, _
        Imaging.ImageLockMode.ReadWrite, _
        Imaging.PixelFormat.Format24bppRgb)
    g_RowSizeBytes = m_BitmapData.Stride

    ' Allocate room for the data.
    Dim total_size As Integer = m_BitmapData.Stride * _
        m_BitmapData.Height
    ReDim g_PixBytes(total_size)

    ' Copy the data into the g_PixBytes array.
    Marshal.Copy(m_BitmapData.Scan0, g_PixBytes, _
        0, total_size)
End Sub

该页面还显示了如何解锁位图。

答案 1 :(得分:0)

这是我认为可能是一个有效的版本:

 
Dim pSmall As Pointer(Of Byte) = CType(CType(smallData.Scan0, 
    Pointer(Of System.Void)), Pointer(Of Byte))

Dim pBig As Pointer(Of Byte) = CType(CType(bigData.Scan0, 
    Pointer(Of System.Void)), Pointer(Of Byte))

Dim smallOffset As Integer = smallStride - smallBmp.Width * 3
Dim bigOffset As Integer = bigStride - bigBmp.Width * 3

Dim matchFound As Boolean = True