我试图像这样在.NetCore 2.1中加载本机库:
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern bool SetDllDirectoryA(string lpPathName);
...
SetDllDirectoryA(pathToDll);
var pDll = LoadLibrary(pathToDll+dllName);
if (pDll == IntPtr.Zero)
{
throw new System.ArgumentException("DLL not found", "pDll");
}
但是函数LoadLibrary始终返回零。 此代码可与.NET Framework完美配合。
我不太确定.NetCore是否支持加载本机库。如果可能的话,正确的方法是什么?
答案 0 :(得分:4)
我认为您正在使用32位DLL。在netcore中,无法使用64位进程加载32位DLL。 尝试以下代码进行检查:
class Program
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
static void Main(string[] args)
{
if (System.Environment.Is64BitProcess)
{
Console.WriteLine("This is 64 bit process");
}
var pDll = LoadLibrary("aDLL.dll");
if (pDll == IntPtr.Zero)
{
Console.WriteLine("pDll: " + pDll);
throw new System.ArgumentException("DLL not found", "pDll");
}
Console.WriteLine("pDll: " + pDll);
}
}
更新:如果要强制NetCore以x86平板(使用32位DLL)运行。首先从https://dotnet.microsoft.com/download/thank-you/dotnet-sdk-2.1.500-windows-x86-installer下载NetCore x86。然后,您应该通过添加.CSPROJ
并将RunCommand
更改为x86来编辑PlatformTarget
文件:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<Prefer32Bit>false</Prefer32Bit>
<PlatformTarget>x86</PlatformTarget>
<Optimize>false</Optimize>
<RunCommand Condition="'$(PlatformTarget)' == 'x86'">$(MSBuildProgramFiles32)\dotnet\dotnet</RunCommand>
<RunCommand Condition="'$(PlatformTarget)' == 'x64'">$(ProgramW6432)\dotnet\dotnet</RunCommand>
</PropertyGroup>
</Project>