【问题标题】:How can I use a C# DLL from Python Script?如何使用 Python 脚本中的 C# DLL?
【发布时间】:2014-08-14 06:59:19
【问题描述】:

我需要从用 C# 编写的 dll 中使用 Python(32) 中的函数。 我使用 ctypes,但我收到错误消息:'找不到 z 函数'。我需要的函数名称是“z”,一个库名称是“ledscrcons.dll”。我已经从另一个应用程序(C#)检查了它,这个库运行良好,但 python 没有看到它。我不知道是什么问题?? 这是PScript的代码:

import sys
import string
from time import gmtime, strftime
from array import *
from ctypes import  *
import ctypes
import clr

def SendStr(s, port):
    mydll = clr.AddReference('ledscrcons.dll')
    from ledscrcons import Class1
    send = mydll.z
    mydll.z.argtypes = [ctypes.c_char_p, ctypes.c_int]
    mydll.z.restype  = c_int
    st = s.encode('cp1251')
    i=2
    count = 0
    critcnt = 1
    while i!=0 and count<critcnt:
        i=send(c_char_p(st), c_int(port))
        if i==2 :
            print(str(i) + "dd")
        if i==1 :
            print(str(i) + 'dd')
        if i==0 :
            print('t')
        count = count + 1
        if count==critcnt:
            if i==1:
                print('kk')
            if i==2:
                print('uu')
    return i

拜托,任何帮助都会很有用。

【问题讨论】:

标签: c# python


【解决方案1】:

我猜你使用的库不是 Com Visible。您可以通过设置属性使其 Com 可见:

[ComVisible(true)]

您还可以尝试 IronPython,它是 Python 的 .net 实现。在 IronPython 中,只需这样做

import clr
clr.AddReference('YourAssemblyName')
from YourNameSpace import YourClassName

【讨论】:

  • 我已经下载了ironP,现在我的代码有错误,你能帮我把这段代码从py32改写成IPython吗?
  • 行中的错误:send = mydll.z(我已经编辑了代码)
  • 我猜是因为脚本找不到.dll。尝试将该 .dll 的路径添加到您的 sys.path。检查这个[链接]stackoverflow.com/questions/1200182/…
  • 另外,导入类后,可以直接使用函数。详情请查看ironpython.codeplex.com/wikipage?title=FAQ
【解决方案2】:

C#-DLL 不是本机可执行文件,但需要 .NET-Runtime 库。因此,您不能将它们与本机 Python 可执行文件一起使用。您必须切换到 IronPython,它是 C# 中的 python 实现。

【讨论】:

    【解决方案3】:

    您不能使用 ctypes 访问 .NET 程序集。 我建议使用IronPythonPython .NET

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-16
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多