Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
HOW TO USE C# GENERATED DLL
#1
Hi,
I developed a C# CLI application with my own functionality , and I have created a .dll with several class to implements the comunications beetween my PC and a extrenal board.

I need to import .dll (C# created), in python because my friend is developing a Qt_py GUI. That GUI will use the class and method present on my .dll.
How can I do?

I saw somenthing, for instance ctypes... If somebody has another idea, It would be good.
Reply
#2
(Jun-09-2023, 12:52 PM)davide_vergnani Wrote: I saw somenthing, for instance ctypes... If somebody has another idea, It would be good.
Yes ctypes or can eg use CFFI, pythonnet.
To show a couple examples found as i have not tried this myself.
import cffi

# Define the C# interface definition
csharp_code = '''
    [DllImport("YourDotNetDLL.dll")]
    public static extern int AddNumbers(int a, int b);
'''

# Create the FFI object
ffi = cffi.FFI()

# Set up the C# code and compile it
ffi.cdef(csharp_code)
lib = ffi.verify('''
    #include <windows.h>
    #include <YourDotNetDLL.h>
''', libraries=["YourDotNetDLL"])

# Call the C# function from the DLL
result = lib.AddNumbers(5, 3)
print("Result:", result)
# pip install pythonnet
import clr
clr.AddReference('path_to_your_dll')

# import the namespace and class

from Namespace import Class

# create an object of the class

obj = Class()

# access functions return type using object

value = obj.Function(<arguments>)
 
Reply
#3
Thanks,
I tried to use clr. It does work, but I have a problem when I try to throw a function, the system cannot find to try a type System.ComponentModel.Componet.

>>> res = box.SetSerial('COM5', 10, pcprot.CCB2);
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
System.TypeLoadException: Could not load type 'System.ComponentModel.Component' from assembly 'System.ComponentModel.Primitives, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
at WiredBoxLib.SerialPortAdapter.get_PortName()
at WiredBoxLib.WiredBox.SetSerial(String port, Int32 txinterval, PC_PROTOCOL protocol)


Above I reported what my python shell reports
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020