-->

Python for .NET “unable to find assembly” error

2019-01-25 07:53发布

问题:

I'm using CPython and I have a C# dll. I'm trying to use Python for .NET to make them talk. I can't use IronPython because I need to integrate this into an existing CPython system.

I'm completely new to Python for .NET, and I actually have very little experience with Python and no experience with C#. So please forgive me if my question seems very basic.

I'm using Python 2.7.3, and I downloaded pythonnet-2.0-alpha2-clr2.0_131_py27_UCS2 and unzipped it into a folder named pyfornet_test, which also contains the dll I'm trying to use (called DotNet4Class.dll)

Then I run this:

import sys

import os

import clr

sys.path.append(r"C:\pyfornet_test")

clr.AddReference("DotNet4Class.dll")

Which gives me this error:

System.IO.FileNotFoundException: Unable to find assembly 'DotNet4Class.dll'.
   at Python.Runtime.CLRModule.AddReference(String name) in C:\Users\Barton\Documents\Visual Studio 2008\Projects\PyShar
p\trunk\pythonnet\src\runtime\moduleobject.cs:line 375

Any advice would be much appreciated. Thank you!

回答1:

Is DotNet4Class.dll built against .NET 4? I assume so based on the naming of the dll.

Note the issue here: http://sourceforge.net/tracker/?func=detail&aid=3293169&group_id=162464&atid=823891

clr.AddReference fails when assembly is built with .NET 4.0 - ID: 3293169

I'd read the solution, but essentially, you need to rebuild and recompile the python for .NET project under .NET 4.

I'll also mention that projects like this, that aren't actively developed and used by lots of people, generally have subtle idiosyncrasies that make knowledge of the platform essential to work around problems such as this. It sounds like you're trying to hack this solution in without understanding much about python or .NET which is always going to be fraught with problems.



回答2:

Try this (without extension .dll):

clr.AddReference(r"C:\pyfornet_test\DotNet4Class")


回答3:

I have code like this (I install MyRightClickMenuService.dll in same directory as my main app). It is built against .Net 4.0.

import clr
import os
import sys
sys.path.append(os.path.dirname(__file__))

clr.AddReference('MyRightClickMenuService')
clr.AddReference('System')
clr.AddReference('System.Security')

from MyRightClickMenuService import (
    AclSecuredNamedPipeBinding,
    MyMenuItem,
    MyContextMenuService,
    etc
)


回答4:

Did you try clr.FindAssembly?

import clr
import sys
assemblydir = r"C:\pyfornet_test"
assemblypath = r"C:\pyfornet_test\DotNet4Class.dll"
sys.path.append(assemblydir)
clr.FindAssembly(assemblypath)

I don't know why it works, but this code works on my computer (Python 2.7, .NET4)