Skip to content

Instantly share code, notes, and snippets.

@NaxAlpha
Created July 14, 2017 14:43
Show Gist options
  • Select an option

  • Save NaxAlpha/8f4e6035a060c6b93fe5d6b8f7bfaeae to your computer and use it in GitHub Desktop.

Select an option

Save NaxAlpha/8f4e6035a060c6b93fe5d6b8f7bfaeae to your computer and use it in GitHub Desktop.
VB.Net implementation of unsafe C# pointers.
'File: Pointer.vb
'Author: Nauman Mustafa
'License: MIT
'Modified: 14-July-2017
'Description: Basic implementation of C++ pointers in VB.NET, is used for unsafe C# code conversion via Telerik Code Converter (Unofficial)
' If you convert c# unsafe code via Telerik code converter, pointers in C# get reference to Pointer(Of T) structure
' It can't be exactly as C# one because there is no function to get pointer of .net variable.
Imports System.Runtime.InteropServices
Public Structure Pointer(Of T As Structure)
Private Shared TypeSize As Integer = Marshal.SizeOf(Of T)
Private ptr As IntPtr
Public Sub New(obj As T)
Throw New Exception("Cannot get pointer of .Net object")
End Sub
Default Public Property Value(idx As IntPtr) As T
Get
Return Marshal.PtrToStructure(Of T)(ptr + CLng(idx) * TypeSize)
End Get
Set(value As T)
Marshal.StructureToPtr(Of T)(value, ptr + CLng(idx) * TypeSize, False)
End Set
End Property
Public Property Target As T
Get
Return Value(0)
End Get
Set(value As T)
Me.Value(0) = value
End Set
End Property
Public Function ToPointer() As IntPtr
Return ptr
End Function
Public Shared Narrowing Operator CType(this As Pointer(Of T)) As T
Return this(0)
End Operator
Public Shared Operator +(this As Pointer(Of T), that As Integer) As Pointer(Of T)
Return this.ptr + that * TypeSize
End Operator
Public Shared Operator -(this As Pointer(Of T), that As Integer) As Pointer(Of T)
Return this.ptr - that * TypeSize
End Operator
Public Shared Narrowing Operator CType(this As Pointer(Of T)) As IntPtr
Return this.ptr
End Operator
Public Shared Widening Operator CType(this As IntPtr) As Pointer(Of T)
Return New Pointer(Of T)() With {.ptr = this}
End Operator
End Structure
'Example usage of pointers in vb.net
Public Module Program
Public Sub Main()
Dim nativePtr = Marshal.AllocHGlobal(12) 'Somehow get void*
Dim p As Pointer(Of Integer) = nativePtr 'Convert it to int*
p(0) = 100 'p[0] = 100; in C++
p += 1 'p++; in C++
p.Target = 200 '*p = 200; in C++
p += 1 'p++; in C++
Dim z As Integer = p 'int z = *p in C++
Dim ptr As IntPtr = p 'convert int* to void*
'Note there is currently no implementation for following
'int a = &z; in C++. Because we can't get variable pointer in .net
End Sub
End Module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment