Python call a dynamic library using pythonnet

Anu Sakpibal
2 min readAug 10, 2021

--

Lecture สั้นๆสำหรับการใช้งาน Python กับ .Net DLL

Photo by Max Kleinen on Unsplash

ขั้นตอนการเรียกใช้งาน .Net DLL ด้วย Python ผ่าน module pythonnet https://github.com/pythonnet/pythonnet

เริ่มต้นด้วยการสร้างไฟล์ DLL ด้วย C# (หากมีไฟล์ DLL อยู่แล้วให้ข้ามไปส่วนของ Python ได้เลย)

การสร้าง DLL File

  1. ทำการ Create Project ที่ Visual Studio (สามารถ Download ได้จาก https://visualstudio.microsoft.com/downloads/)
    เลือก “File” -> “New” -> “Project…” จากนั้นเลือก “C# Class Library (.Net Framework)”

เมื่อ Create Project เสร็จแล้ว ก็เขียน Code ตามต้องการ หรือจะลองนำ Code ตามตัวอย่างด้านล่างไปใช้งานก็ได้

2. จาก Code ด้านบน ผมตั้งชื่อ namespace เป็น Showmessage และ class name เป็น MSGShow และมีฟังก์ชัน Happy กับ Sad เพื่อ return message

หลังจากสร้าง Code เสร็จ ก็ทำการ Build solution หรือกดคีย์ F6 หากไม่มีข้อผิดพลาด เราจะได้ไฟล์ DLL อยู่ใน Directory “bin/debug” ของโปรเจ็คที่เราสร้าง

มาถึงฝั่งของ Python สำหรับเรียกใช้งานไฟล์ DLL

  1. ทำการติดตั้ง module pythonnet ด้วยคำสั่ง
pip install pythonnet

หลังจากติดตั้งโมดูล pythonnet เรียบร้อยแล้วให้ทำการตรวจสอบ module ด้วยคำสั่ง clr.__version__

>>> import clr
>>> clr.__version__
‘2.5.1’

2. ส่วนของ Code Python ในการเรียกใช้งาน DLL ตามด้านล่าง

มีข้อสังเกตใน Code Python ดังนี้

  • assemply_path เรียกไปยัง Directory ที่เรา build DLL ไฟล์ไว้ จาก Code ด้านบนก็คือ
assembly_path = r”D:\workspace\Showmessage\bin\Debug”
  • import DLL โดยไม่ต้องใส่ .dll ตามหลังชื่อไฟล์
clr.AddReference("Showmessage")

ชื่อไฟล์ DLL หลังจากเรา build แล้วจะเหมือนกับชื่อ name space หากไม่ต้องการให้ชื่อไฟล์ DLL เหมือนกับ name space สามารถเปลี่ยนได้ แต่ใน Lecture นี้ผมไม่ได้เปลี่ยน ดังนั้น ตอนเรา AddReference ก็จะใช้ชื่อ “Showmessage” เหมือนเดิม

  • เรียกใช้ name space ของ C# ผ่านการ import module
from Showmessage import MSGShow
  • จากนั้นก็เรียกใช้งาน Method และส่งผ่าน Parameter ตามที่เราต้องการ
msg = MSGShow()print(msg.Happy("python"))print(msg.Sad("Golang"))

เมื่อทดลองรัน จะได้ผลลัพธ์ตามด้านล่าง

เสร็จพิธี

ที่มาของ Lecture นี้สามารถดูเพิ่มเติมได้จาก https://github.com/pythonnet/pythonnet/wiki/How-to-call-a-dynamic-library

--

--

Anu Sakpibal

I’m miscellaneous developer. Work with Javascipt, C#, Python, iot @Dectre <code ’n’ craft lover/> https://github.com/nuSapb