本想在网上搜一下,如果在x64平台下,混合调用用c++写的x32, x64 动态链接库。
但在网上有找到是说如果判断当前平台是x32还是x64, 然后调用不同路径下面的用c#写的dll(同样的代码在x32,x64下不同编译结果).有一定的参考价值。记录下来
public static class MultiplatformDllLoader
{
private static bool _isEnabled;
public static bool Enable
{
get { return _isEnabled; }
set
{
lock (typeof (MultiplatformDllLoader))
{
if (_isEnabled != value)
{
if (value)
AppDomain.CurrentDomain.AssemblyResolve += Resolver;
else
AppDomain.CurrentDomain.AssemblyResolve -= Resolver;
_isEnabled = value;
}
}
}
}
/// Will attempt to load missing assembly from either x86 or x64 subdir
private static Assembly Resolver(object sender, ResolveEventArgs args)
{
string assemblyName = args.Name.Split(new[] {','}, 2)[0] + ".dll";
string archSpecificPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
Environment.Is64BitProcess ? "x64" : "x86",
assemblyName);
return File.Exists(archSpecificPath)
? Assembly.LoadFile(archSpecificPath)
: null;
}
}
另外:若想在64位平台下调用32位用c写成的dll, 那么在vs中编译时,要选择与32相同的编译选项,否则会出错。
同时,调用c写的dll时,要注意调用转换要正确。如:
[DllImport("dgsdk.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int ShortRandom(int from, int to);
如果不加CallingConvention = CallingConvention.Cdecl 也会出错。
网上有开源的interop的工具,可以使用,但似乎只是为win32 api而设计的。http://clrinterop.codeplex.com/releases/view/14120