【问题标题】:Using .PYD file in C#?在 C# 中使用 .PYD 文件?
【发布时间】:2018-03-01 06:22:21
【问题描述】:

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

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

【问题讨论】:

  • 闻起来像 X-Y-问题。你想做什么在 C# 中很难,但在 Python 中却很容易?
  • 您可以尝试使用 IronPython 脚本宿主。
  • 你试过pythonnet吗? github.com/pythonnet/pythonnet

标签: c# python pyd


【解决方案1】:

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


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

【讨论】:

  • 嘿,这适用于 Python 2。此外,您需要通过 python.dll API 才能使其工作,Pythonnet 就是这样做的。检查我的答案。
【解决方案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()

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

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

scope.Eval(expr)

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

scope.Get(variableName)

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

参考文献

0:https://codereview.stackexchange.com/questions/160524/evaluating-arithmetic-expressions
1:https://www.programiz.com/python-programming/methods/built-in/eval
2:What does Python's eval() do? 在 SO
3:https://docs.python.org/3/reference/expressions.html
4:Python - Evaluate math expression within string 在 SO
5:@ 987654334@
6: https://www.w3schools.com/python/python_variables.asp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 2020-02-26
    • 2016-08-30
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多