C#調用pyd

  • 2020 年 11 月 17 日
  • 筆記

python打包成pyd在本篇部落格不多敘述,請讀者自行百度,本篇部落格主要講解在C#中如何調用pyd以及遇到的一些問題如何解決。

1.安裝pythonnet

pythonnet是一個強大的工具包,用於C#程式碼與python程式碼進行交互,不僅可以實現在C#中調用python,也可以實現在python中調用C#.

GitHub://github.com/pythonnet/pythonnet

  • 首先打開nuget包管理器:
    Alt
  • 根據你python的版本下載對應的pythonnet,筆者使用的是python3.6,所以下載的是py36。
    Alt

2.調用pyd中的模組

  • 首先引用pythonnet:
using Python.Runtime;
  • 調用pyd的模組:
//All calls to python should be inside a using (Py.GIL()) {/* Your code here */} block.
using (Py.GIL())
{
	//Import python modules using dynamic mod = Py.Import("mod"), then you can call functions as normal.
	//All python objects should be declared as dynamic type.
	dynamic np = Py.Import("test_pyd");
	np.hello();
	Console.ReadKey();
}

Alt

  • python程式碼:
def hello():
    print("Hello world")

3.可能出現的問題及解決方案

  • 環境變數的配置,環境變數的對應路徑的python版本需要與你下載的pythonnet包版本是相同的:
    Alt
    筆者電腦中有不同版本的python,經過筆者測試後發現更換版本最簡單的方式是替換環境變數的順序,筆者是在win10系統下進行的測試,其他系統未進行過測試。
    另外要注意你的pyd如果是使用64位編譯的,則環境變數對應的python版本也需要是64位的。
    當python368在上時:
    Alt
    當python378在上時:
    Alt
  • System.DllNotFoundException:「無法載入 DLL「python36」: 找不到指定的模組。
    Alt
    解決方案:將python文件夾中的python36.dll複製到debug目錄下
    Alt
  • Python.Runtime.PythonException:「ModuleNotFoundError : No module named ‘test_pyd’」

Alt
解決方案:將test_pyd.pyd放入debug目錄下
Alt

  • System.MissingMethodException:「Method not found: ‘System.Reflection.Emit.AssemblyBuilder System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, System.Reflection.Emit.AssemblyBuilderAccess)’.」
    Alt
    解決方案:該問題是由於.NET框架所導致的,筆者在使用.NET Core 3.1的時候就會出現這個錯誤,更換為.NET Framework 4.7.2後問題解決。
    Alt
    在這裡插入圖片描述