Hello all,

I'm new to VB.NET. Does anyone know how to call non-.NET functions (i.e. native, unmanaged) in dll files where you don't know the dll filename until run time?

I had a go using LoadLibrary and GetProcAddress with delegates, but ended up with a mess (a working mess - but a mess all the same). I couldn't cast the procedure address (int32) to a delegate, and had to declare GetProcAddress as returning a delegate.

So my code is:

Private Declare Function LoadLibrary Lib "kernel32.dll" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As Int32
    Private Declare Function GetProcAddress Lib "kernel32.dll" (ByVal hModule As Int32, ByVal lpProcName As String) As asdf

    Delegate Function asdf(ByVal i As Int32) As Int32

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Static dll_loaded As Boolean, dll_handle As Int32, msg_fn_addr As asdf, msgfn As asdf
        If Not dll_loaded Then
            dll_handle = LoadLibrary("c:\documents\code\dev-cpp\projects\quickdll.dll")

            If dll_handle = 0 Then
                MsgBox("LoadLibrary failed")
                Return
            Else
                dll_loaded = True
            End If


            msgfn = GetProcAddress(dll_handle, "msg")
            'can't check return value!!
        End If

        Try
            Debug.Print(msgfn.Invoke(533).ToString)

        Catch ex As Exception
            Debug.Print(ex.GetType.ToString & " " & ex.ToString)
        End Try
    End Sub

what I was trying (and failing) was msgfn = directcast(getprocaddress(dll_handle, "msg"), form1.asdf), with getprocaddress returning Int32, which vb.net didn;t like at all.

Any help would be appreciated heaps!!
-Doug

OK. After too much effort I've got a less-messy solution.

A delegate is created for every imported function signature. Functions loaded with getprocaddr (as IntPtr) are cast using the marshaling class something like: msg_fn = GetDelegateForFunctionPointer(GetProcAddressMsg(dll_handle, "msg"), GetType(msg)) .NET might need a bit of getting used to I think...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.