简体   繁体   English

如何使用Python脚本中的C#DLL?

[英]How can I use a C# DLL from Python Script?

I need to use a function in Python(32) from dll written in C#. 我需要使用C#编写的dll在Python(32)中使用一个函数。 I use ctypes, but i got the error message:'can't find z function'. 我使用ctypes,但收到错误消息:“找不到z函数”。 The name of the funct i need is 'z' an lib name is "ledscrcons.dll". 我需要的功能名称是“ z”,库名称是“ ledscrcons.dll”。 I've checked it from another app(C#) and this library works good, but python doesn't see it. 我已经从另一个应用程序(C#)中检查了它,并且该库运行良好,但是python没有看到它。 I have no idea what is the problem?? 我不知道是什么问题?? Here is the code of PScript: 这是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

Please,any help would be usefull. 请,任何帮助将是有用的。

I guess the library you used is not Com Visible. 我猜您使用的库不是Com Visible。 You can make it Com Visible by setting attribute: 您可以通过设置属性使其可见:

[ComVisible(true)]

You can also try IronPython, which is a .net implementation of Python. 您也可以尝试IronPython,它是Python的.net实现。 In IronPython, simply do 在IronPython中,只需执行

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

C#-DLLs are not native executables but need the .NET-Runtime library. C#-DLL不是本机可执行文件,但需要.NET-Runtime库。 So you cannot use them with native Python executables. 因此,您不能将它们与本机Python可执行文件一起使用。 You have to switch to IronPython which is a python implementation in C#. 您必须切换到IronPython,这是C#中的python实现。

You cannot use ctypes to access a .NET assembly. 您不能使用ctypes访问.NET程序集。 I would recommend using IronPython or Python .NET 我建议使用IronPythonPython .NET

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM