简体   繁体   中英

DLLImport fails to find the DLL file

I have a C# application which needs to import a function from a C++ dll. I use DLLImport to load the function. It works fine in English and Chinese environment, but it always raise 'Module not found' exception in French operating system.

The code snapshot:

[DllImport("abcdef.dll", CallingConvention = CallingConvention.StdCall)]
public static extern string Version();

Note that letters in the name of module have been replaced but the name itself is in the same format and the same length.

And a screenshot: 在此处输入图片说明

Any ideas?

I have tried all methods you proposed, however the problem still exists.

Here is an alternative way which could avoid that error. It uses Win32 APIs to load the library and find the address of the function, then invoke it. Demo code follows:

class Caller
{
    [DllImport("kernel32.dll")]
    private extern static IntPtr LoadLibrary(String path);
    [DllImport("kernel32.dll")]
    private extern static IntPtr GetProcAddress(IntPtr lib, String funcName);
    [DllImport("kernel32.dll")]
    private extern static bool FreeLibrary(IntPtr lib);

    private IntPtr _hModule;

    public Caller(string dllFile)
    {
        _hModule = LoadLibrary(dllFile);
    }

    ~Caller()
    {
        FreeLibrary(_hModule);
    }

    delegate string VersionFun();

    int main()
    {
        Caller caller = new Caller("abcdef.dll");
        IntPtr hFun = GetProcAddress(_hModule, "Version");
        VersionFun fun = Marshal.GetDelegateForFunctionPointer(hFun, typeof(VersionFun)) as VersionFun;
        Console.WriteLine(fun());

        return 0;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM