Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 943
dergroncki Avatar asked Mar 05 '26 13:03

dergroncki


1 Answers

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>
like image 86
Khai Nguyen Avatar answered Mar 08 '26 03:03

Khai Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!