Click here to Skip to main content
15,892,839 members
Articles / Programming Languages / Objective C

Using C Calling Convention Callback Functions in C# and VB - The Easy Way

Rate me:
Please Sign up or sign in to vote.
5.00/5 (31 votes)
13 Sep 20053 min read 318.5K   4K   68  
Provides an easy way to use C calling convention callback functions in C# and VB
Imports System
Imports System.Runtime.InteropServices
Imports App.Runtime.InteropServices

Module DelegateGeneratorDemoVB

    Public Delegate Sub CallbackDelegate(ByVal count As Integer)

    Overloads Sub SetCallback(ByVal callback As CallbackDelegate)
        SetCallback(DelegateGenerator.CreateDelegate(callback))
    End Sub

    <DllImport("TestLib.dll", CallingConvention:=CallingConvention.Cdecl)> _
    Overloads Sub SetCallback(ByVal callback As MulticastDelegate)
    End Sub

    <DllImport("TestLib.dll", CallingConvention:=CallingConvention.Cdecl)> _
    Overloads Sub InvokeCallback()
    End Sub

    Sub Main()
        Dim del As CallbackDelegate = AddressOf Callback

        Console.WriteLine("Testing generated delegate...")

        SetCallback(del)

        Try
            For i As Integer = 0 To 9 Step 1
                InvokeCallback()
            Next i
        Catch exc As Exception
            Console.WriteLine(exc)
        End Try

        Console.WriteLine("Testing direct delegate usage...")

        SetCallback(DirectCast(del, MulticastDelegate))

        Try
            For i As Integer = 0 To 9 Step 1
                InvokeCallback()
            Next i
        Catch exc As Exception
            Console.WriteLine(exc)
        End Try
    End Sub

    Sub Callback(ByVal count As Integer)
        Console.WriteLine("Callback invoked for " & count & " time")
    End Sub

End Module

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


Written By
Software Developer (Senior)
Bulgaria Bulgaria
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions