V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ge2009
V2EX  ›  Python

请教 Python 怎么调用 C#的 dll

  •  
  •   ge2009 · 2018-01-20 10:25:20 +08:00 · 7417 次点击
    这是一个创建于 2259 天前的主题,其中的信息可能已经有所发展或是发生改变。

    例有下一个用 C#写的 test.dll 里面有 test 的 NameSpace, Class1 的类,一个 returnstr 的方法

    我的方法是:

    import clr
    test = clr.AddReference("test")
    print test.returstr
    
    

    这样的结果返回说

    AttributeError: 'RuntimeAssembly' object has no attribute 'returstr'
    

    问题 1:

    网上也找了一些资料,看了 Python.Net 的资料好像也是这么写的,方法名应该也没错,比较奇怪,求解

    问题 2: 有没有什么工具可以看到 dll 里面的方法名称?

    附件 test.dll 地址: https://pan.baidu.com/s/1dvge54

    12 条回复    2018-01-20 15:24:50 +08:00
    lynnX
        1
    lynnX  
       2018-01-20 10:30:10 +08:00   ❤️ 1
    问题一 不知道 问题二 .Net Reflector 或者 ILSpy
    ge2009
        2
    ge2009  
    OP
       2018-01-20 11:02:31 +08:00
    @lynnX 嗯,问题 2 我也刚安装了,现在就是问题一比较奇怪,已经确认了方法名应该都没错的.
    Athrob
        3
    Athrob  
       2018-01-20 11:46:32 +08:00
    Class1 呢?
    ge2009
        4
    ge2009  
    OP
       2018-01-20 12:23:30 +08:00
    @Athrob 他们 Python.net 的文档里面好像是直接调就可以了,试过先 import Class1 好像也还是一样报错
    iilxy
        5
    iilxy  
       2018-01-20 13:13:20 +08:00 via iPhone   ❤️ 1
    .net 的要用 ironpy 来调用吧
    asuraa
        6
    asuraa  
       2018-01-20 14:31:06 +08:00 via iPhone   ❤️ 1
    楼上正解 使用 ironpython 遗憾的是只支持 py2
    haddy
        7
    haddy  
       2018-01-20 14:34:54 +08:00
    试试
    `import clr
    clr.AddReference("test")
    import test
    print test.returstr
    ` ?
    haddy
        8
    haddy  
       2018-01-20 14:39:37 +08:00
    呃,不好意思,我弄错了。不要在意我刚才的回复。
    haddy
        9
    haddy  
       2018-01-20 14:44:15 +08:00
    用 clr.System.Reflection.Assembly.LoadFile
    haddy
        11
    haddy  
       2018-01-20 15:18:39 +08:00   ❤️ 1
    囧,不好意思。就我现在搜集到的信息,DLL 的目标版本需为 .NET 4.0+,不然要设置某个环境变量。这个原因也有可能。然后除了上面的方法,似乎还可以 clr.AddReferenceToFileAndPath,这样相比 AddReference 就不用手动将路径添加到 sys.path 里。但具体是否可行我也说不清楚……
    ge2009
        12
    ge2009  
    OP
       2018-01-20 15:24:50 +08:00
    @iilxy
    @luodaoyi
    感谢二位,已经解决了确实是用 ironpython 可以处理,原先的时候把它和 Python For .net 搞混了.
    同时也带话 @hadyy 哈.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3940 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:24 · PVG 18:24 · LAX 03:24 · JFK 06:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.