如何在 Python 脚本中使用 C# DLL?
我需要在Python(32位)中使用一个用C#写的dll里的函数。
我使用了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
请帮帮我,任何帮助都会很有用。
3 个回答
0
C#的DLL文件不是直接可以运行的程序,它们需要.NET运行库来支持。所以,你不能直接在原生的Python程序中使用它们。你需要使用IronPython,这是一种用C#实现的Python版本。
0
你不能用ctypes来访问一个.NET的程序集。 我建议你使用 IronPython 或者 Python .NET。
1
我想你用的那个库可能没有设置为可被COM访问。你可以通过设置一个属性来让它变得可被COM访问:
[ComVisible(true)]
你也可以试试IronPython,它是Python在.net上的一个实现。在IronPython中,只需要这样做:
import clr
clr.AddReference('YourAssemblyName')
from YourNameSpace import YourClassName