Help us understand the problem. What is going on with this article?

DllImportで実行時にdllを指定するには?

More than 3 years have passed since last update.

概要

C++で作られたネイティブなDLLは、x86用、x64用に分かれている場合がある。

問題点
DllImportては、dll名がコンパイル時に決定されてしまうのでx86/x64でそれぞれ異なるdllを指定できない。
つまり、実行時に決めることができない。

結論
DllImportでdllを読み込む前にLoadLibrary関数でDLLを読み込んでおくことで同名のdllは、今後、読み込み済みのDLLを参照するようになる。

コード

internal class NativeMethods {
    [DllImport("kernel32")]
    private static extern IntPtr LoadLibrary( string lpFileName );

    const string dllName = "SQLite.Interop.dll";

    static NativeMethods() {
        if( Environment.OSVersion.Platform == PlatformID.Unix ) {
            return;
        } else {
            var dllPath = Path.Combine( Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location ) , Environment.Is64BitProcess ? @"x64" : @"x86" , dllName );
            if( !( File.Exists( dllPath ) && LoadLibrary( dllPath ) != IntPtr.Zero ) )
                throw new DllNotFoundException( dllPath );
        }
    }

    [DllImport(dllName , EntryPoint = "sqlite3_errmsg" , CallingConvention = CallingConvention.Cdecl)]
    internal static extern IntPtr sqlite3_errmsg( IntPtr dbHandle );
}
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away