3

I am currently using Python for .NET to call methods from a C# DLL. Here is my code :

# Common Language Runtime
import clr
# Import DLL
clr.AddReference("MyDLL")
# Import class
from MyNamespace import MyClass
# Instantiation
my_instance = MyClass()
# Call methods
my_instance.myMethod()

Now, I'd like to unload and remove the DLL reference after I'm done with my instance so I can do whatever I have to do with the DLL file (like regenerate it). I've read the Python for .NET documentation but I couldn't find anything about this issue.

denfromufa
  • 5,610
  • 13
  • 81
  • 138
Vincent
  • 12,919
  • 1
  • 42
  • 64
  • is `MyClass` part of `MyDLL`? – ryrich Dec 05 '13 at 16:00
  • yep, it is a C# class from the namespace of the DLL – Vincent Dec 05 '13 at 16:06
  • I think I remember how loading assemblies works in C#... That is, when loading assemblies, it is loaded in a context. You cannot remove an individual assembly from this context until the process is closed. Perhaps it is similar in Python .NET. Is there an error you are getting if you don't remove the reference? – ryrich Dec 05 '13 at 16:09
  • I think you're right. I'm not getting any error from python, but if I try to delete my file for instance, windows will show : "The action cannot be completed because the file is open in pythonw.exe" – Vincent Dec 05 '13 at 16:18
  • Did you ever find a solution to this @Vincent? Using C++ and Pythonnet i need to also be able to unload a DLL reference. – user1024792 Jan 08 '18 at 19:26

1 Answers1

4

Here's a similar question that was posted on SO. Jon seems to echo what I said - you cannot remove a single reference from the context (AppDomain).

I ran into a code segment online that uses this piece of code:

clr.ClearProfilerData() #unload the .dll file so the file lock is released

I'm assuming you want to unload the DLL because you want to recompile it but the compiler is complaining a process is still using it? Perhaps using the method above will release it?

EDIT: Just as a follow-up, if you wanted to research into it more, try out this idea. That is, create an instance of Python in C#, load it in a custom AppDomain, and unload the custom AppDomain when finished. :)

Community
  • 1
  • 1
ryrich
  • 2,164
  • 16
  • 24
  • 1
    This is exactly what I need. The only problem is that my `clr` module doesn't have the `ClearProfilerData` function. Maybe it is not implemented in Python for .NET. Thanks for your help anyway ! – Vincent Dec 05 '13 at 16:25