pythonc#.netdllpython.net

Calling C# DLL in Python TypeLoadException error


Could you please help what could be the problem?

I have the following C# code:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;


namespace PostMessage
{
    public class Message
    {
        public async Task<string> SendMessage()
        {    
            .... code here to create the message body
            HttpResponseMessage response = await client.PostAsync(url, request);
            string responseXml = await response.Content.ReadAsStringAsync();
            return responseXml;
        }


        public string RunSync()
        {
            var task = Task.Run(async () => await SendMessage());
            return task.Result;
        }

    }
}

I created from this a .DLL file and called from Python.

import clr
clr.AddReference("/PostMessage.dll")
from PostMessage import Message

When I run the code I got the following error:

TypeLoadException: Could not load type 'System.Diagnostics.DebuggerStepThroughAttribute' from assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

In C# I used .NET 5. In Python I used pythonnet 3.0.1


Solution

  • Your C# code has dependencies on other parts of the framework. Right now you are only loading the dll itself, without taking into account the rest of the dependencies:

    from pythonnet import load
    load("coreclr")
    
    import clr
    clr.AddReference("/PostMessage.dll")
    from PostMessage import Message
    

    If you have multiple core runtimes and you don't want it auto resolved you can follow this here

    from pythonnet import load
    
    load("coreclr", runtime_config="/path/to/runtimeconfig.json")
    

    You must also make sure that you have indeed installed the .net core of approrpiate version into the default location.