3

我正在使用 C# 开发一个程序,但我刚刚发现我要编写的程序在 C# 中非常非常困难,但在 Python 中却很容易。所以我想做的是制作一个.PYD文件并在 C# 程序中使用它,但我不知道如何。我一直在寻找它,但我找不到任何东西。

所以这些是我的问题:如何.PYD在 C# 中使用文件?我知道.PYD文件类似于.DLL文件,那么.PYD文件在没有安装 Python 的计算机上仍然可用吗?

4

2 回答 2

2

使用pythonnet

教程

你需要一个 GIL 状态。

using (Py.GIL())
{
    // Your code here
}

在 GIL 块内,创建一个范围。

using (Py.GIL())
{
    using (PyScope scope = Py.CreateScope())
    {
        // Your code here
    }
}

要执行代码:

scope.Exec(codeStr);

设置变量:

scope.Set(name, value); // 'name' is a string and 'value' is a 'PyObject' object.

转换为PyObject

obj.ToPython()

PyObject如果您需要将对象放入 Python,请转换为。

评估[0] [1] [2] [3] [4]一个表达式

scope.Eval(expr)

要获取变量[5] [6]值:

scope.Get(variableName)

在任何注释前没有结束分号并且是单行的 C# 代码表示一个表达式

参考

0:https
://codereview.stackexchange.com/questions/160524/evaluate-arithmetic-expressions 1:https
://www.programiz.com/python-programming/methods/built-in/eval 2:Python 的 eval 是什么() 做?在 SO
3 上:https
://docs.python.org/3/reference/expressions.html 4: Python -在 SO 5上的字符串中评估数学表达式: https ://realpython.com/python-variables 6:https:// /www.w3schools.com/python/python_variables.asp

于 2019-07-09T15:58:53.793 回答
2

.pyd 文件是一个 DLL,但具有函数 init*() 其中 * 是 .pyd 文件的名称。例如, spam.pyd 有一个名为initspam(). 它们不仅相似,而且相同!它们可以在没有 Python 的 PC 上使用


不要忘记:内置函数将不可用。在 C 中搜索它们,在 Cython 代码中将它们添加为 extern 并编译!

于 2017-09-20T12:22:11.847 回答