简体   繁体   中英

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

I need to use a function in Python(32) from dll written in C#. I use ctypes, but i got the error message:'can't find z function'. The name of the funct i need is 'z' an lib name is "ledscrcons.dll". I've checked it from another app(C#) and this library works good, but python doesn't see it. I have no idea what is the problem?? Here is the code of 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. You can make it Com Visible by setting attribute:

[ComVisible(true)]

You can also try IronPython, which is a .net implementation of Python. In IronPython, simply do

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

C#-DLLs are not native executables but need the .NET-Runtime library. So you cannot use them with native Python executables. You have to switch to IronPython which is a python implementation in C#.

You cannot use ctypes to access a .NET assembly. I would recommend using IronPython or Python .NET

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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