How can I get the current filename in a FreeBasic DLL?

178 Views Asked by At

How can make a FreeBASIC DLL find its own filename and path? I've tried this so far: (ran it with rundll32 filename,DllMain) Code:

#include "windows.bi"
Extern "Windows-MS"
Sub DllMain() Export
    dim This as String
    This = dir(command$(0))
    MessageBox( null, "Hello World", This, MB_OK )
End Sub
End Extern

. . . but it doesn't work.

When I compile it as an EXE though, it works fine.

Any suggestions? Thanks!

1

There are 1 best solutions below

0
MrSnrub On

I tried to adapt the approach of this C++ snippet to FreeBASIC. At first glance, it seems to work. But: Snippet provided "as is", without warranty of any kind. Use at your own risk.

#include "windows.bi"

Const GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT = &H2
Const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = &H4

Extern "Windows-MS"

Function getMyPath() As String
    ' See https://stackoverflow.com/a/6924332/ 
    Dim path As ZString * 255
    Dim hm As HMODULE = NULL
    If GetModuleHandleEx( _
            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS Or _ 
            GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, _
            Cast(LPCSTR, @getMyPath), _
            @hm _ 
        ) Then
            GetModuleFileName( hm, path, SizeOf( path ) )
    End If
    Return path
End Function

Sub DllMain() Export
    dim dllPath as String
    dllPath = getMyPath()
    MessageBox( null, dllPath, "Hello World", MB_OK )
End Sub

End Extern