Question

Given

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern int GetDllDirectory(int nBufferLength, StringBuilder lpPathName);

StringBuilder tmp = new StringBuilder(10240);
if (GetDllDirectory(10240, tmp) == 0)
{
 int err = Marshal.GetLastWin32Error();
}

MSDN states that

If the function succeeds, the return value is the length of the string copied to lpBuffer, in characters.

I receive 0, err is 0 too. What can be wrong here?

Was it helpful?

Solution

The default value for the DLL directory is empty. The return value of zero that you are seeing simply tells you that there is nothing to retrieve.

You have to set the DLL directory to something before you can expect GetDllDirectory to return anything other than zero. Add a call to SetDllDirectory before you call GetDllDirectory to convince yourself of this. Or try calling from a simple C++ program and also observe the exact same behaviour.

The documentation is certainly misleading here. I'm not sure how you distinguish actual failure from no value being set. Perhaps GetLastWin32Error() will return a non zero value in case of error. That said, there are very few failure modes. Personally I'd be inclined to treat zero as meaning that the DLL directory has no value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top