dergroncki
dergroncki

Reputation: 798

load native libraries in .NetCore 2.1 (Windows)

I am trying to load native libraries in .NetCore 2.1 like this:

[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");
}

But the function LoadLibrary returns zero always. This code works fine with .NET Framework.

I am not really sure if loading native libraries is supported in .NetCore. If it is possible what is the correct way to do it?

Upvotes: 3

Views: 2945

Answers (1)

Khai Nguyen
Khai Nguyen

Reputation: 945

I think you are using a 32 bit DLL. In netcore, a 32bit DLL could not be loaded with a 64bit process. Try this code to check:

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);
        }
    }

Update: If you want to force NetCore runs at x86 flatform (to use 32bit DLL). First download NetCore x86 from https://dotnet.microsoft.com/download/thank-you/dotnet-sdk-2.1.500-windows-x86-installer. Then you should edit .CSPROJ file by adding RunCommand and changing PlatformTarget to x86 :

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

Upvotes: 4

Related Questions