How to load a C# dll in python?

南笙酒味 提交于 2019-11-26 04:45:27

问题


how can I load a c# dll in python?

Do I have to put some extra code in the c# files? (like export in c++ files)

I don\'t want to use IronPython. I want to import a module to Python!


回答1:


This is to answer the second part of your Question Try making the DLL COM visible.

by using the

[ComVisible(true)]

Ok IronPython is a .net implemenatation of the Python language The technology is going to use the DLR of the .net 4.0 when it arrives so IronPython will have more Dynamism (is that a word). (In english if you're a Python guru, you'll feel more at home when you use IronPython)

So you may well choose IronPython, if you do that you can skip the COM visible part. Since both (C# , Iron Python) are under .Net

http://ironpython.net/

Visit here for a sample C# DLL which is visible to COM




回答2:


The package Python for.NET and the Python Implementation IronPython now work the same way.

Example for a C# DLL MyDll.dll:

import clr
clr.AddReference('MyDll')
from MyNamespace import MyClass
my_instance = MyClass()

See this post for more details.




回答3:


Python for .NET works well if you don't want to use IronPython.




回答4:


If you do not want to use solutions like Python .NET or IronPython it is possible to implement a C++/CLI wrapper and use Pythons ctypes in order to load it. For example:

The C++/CLI library CallCSharp:

extern "C" {
    __declspec(dllexport) void foo()
    {
        // here you could use managed and unmanaged code
        Console.WriteLine("Hello, C# world...");
    }

The Python script:

from ctypes import cdll
lib = cdll.LoadLibrary("./CallCSharp.dll")
lib.foo()

I strongly recomment reading this blog: http://pragmateek.com/if-your-plumbing-doesnt-work-youre-just-not-using-enough-pipes/#more-1745

It also handles the issue that arises when the C++/CLI wrapper calls code that is in another assembly (you'd get something like a WindowsError: [Error -532462766] Windows Error 0xE0434352 from your Python script then).



来源:https://stackoverflow.com/questions/2077870/how-to-load-a-c-sharp-dll-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!