Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why LoadLibrary not working with the given path?

Tags:

c#

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.

like image 476
vivek nuna Avatar asked Feb 22 '26 00:02

vivek nuna


2 Answers

You have to set the character set used to Unicode, since you use non-unicode character in your path:

[DllImport("kernel32", CharSet=CharSet.Unicode)]
static extern IntPtr LoadLibrary(string lpFileName);

Now it takes the LoadLibraryA (ANSI) variant. See MSDN.

like image 136
Patrick Hofman Avatar answered Feb 23 '26 16:02

Patrick Hofman


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).

like image 44
David Haim Avatar answered Feb 23 '26 16:02

David Haim