vivek nuna vivek nuna - 9 days ago 5
C# Question

Why LoadLibrary not working with the given path?

I'm trying to call

LoadLibrary
method, But it returns 0.
Marshal.GetLastWin32Error
is returning 126 (The specified module could not be found.).

Code:

[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);

string path = @"C:\junk\测试\BlueStacksKK_DeployTool_2.5.48.7209_china_gmgr\ProgramFiles\BstkC.dll";
IntPtr ptr = LoadLibrary(path);
int error = Marshal.GetLastWin32Error();


But If I move this file to some other location like
C:\Test\BstkC.dll
, it works fine.

Issue could be due to
测试
in path. So If we have direcotry in other languages other then English, how will it work.

Just for your information.
File.Exists(path)
returns true.

Answer

Try:

[DllImport("kernel32", SetLastError = true]
static extern IntPtr LoadLibraryW([MarshalAs(UnmanagedType.LPWStr)]string lpFileName);

The underlying Win32 API comes with two flavors: ASCII mode (which allows only ASCII characters in strings) and Unicode Mode (which allows UTF16 characters in strings).

C# is UTF16 based, basically, you invoked a ASCII-flavored function with UTF16 string, you need to explicitly tell the CLR you want the Unicode flavored function (LoadLibraryW) and retain the UTF16 encoding of the C# string (by using LPWStr).