4

I'm trying to use pythonnet to call .NET code from python but I'm getting an import error on my compiled assembly. I was able to produce the following mwe.

Folder structure:

pynet/
    TestPyCS/
        TestPyCS/
            bin/
                Debug/
                    TestPyCS.dll
                    TestPyCS.pdb
            TestCs.cs
    test.py

The C# project contains only one file (TestCs.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestPyCS
{
    public class TestCS
    {
        public string Test()
        {
            return "test";
        }
    }
}

That I'm building with target .NET Framework 4.7.2

Python code (in test.py):

import clr
import os
import sys

abshere = os.path.dirname(os.path.abspath(__file__))
dlldir = os.path.join(abshere, "TestPyCS", "TestPyCS", "bin", "Debug")

sys.path.append(dlldir)

print(clr.FindAssembly("TestPyCS"))
print(clr.AddReference("TestPyCS"))

# this is just for testing pythonnet
from System import Console
Console.WriteLine("Hello world!")


import TestPyCS
print(dir(TestPyCS))

from TestPyCS import TestCS

t = TestCS()

print(t.Test())

And the output I'm getting is:

D:\path\to\pynet\TestPyCS\TestPyCS\bin\Debug\TestPyCS.dll
TestPyCS, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
Hello world!
['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
Traceback (most recent call last):
  File ".\test.py", line 21, in <module>
    from TestPyCS import TestCS
ImportError: cannot import name 'TestCS'

I already looked into the following questions:

ModuleNotFoundError when importing a .NET custom class in pythonnet

Python for .Net Error: ImportError: No module named

but I was not able to solve the issue.

Daniele
  • 153
  • 3
  • 11

0 Answers0