【问题标题】:How to call a C# code from python [duplicate]如何从python调用C#代码[重复]
【发布时间】:2017-05-22 07:37:51
【问题描述】:

我编写了一个用于连接 Microsoft SharePoint 的 C# 代码,但我需要从 python 调用它,这意味着我想要求 python 运行此代码,可以吗? 如果是,我该怎么做?

【问题讨论】:

  • 这不是重复的,因为这与从 Python 调用外部脚本不是同一个问题。有关详细信息,请参阅答案。

标签: c# python web-services sharepoint


【解决方案1】:

简短的回答是

os.system("myapp.exe")

【讨论】:

  • 别忘了import os
  • 如果你为这个明显的欺骗提供了一个答案,至少要正确地做到这一点。 os.system 已弃用,subprocess 模块是首选方式。并且应该检查返回码。
【解决方案2】:

其实很简单。只需使用 NuGet 将“UnmanagedExports”包添加到您的 .Net 项目。详情请见https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports

然后您可以直接导出,而无需执行 COM 层。这是示例 C# 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using RGiesecke.DllExport;

class Test
{
    [DllExport("add", CallingConvention = CallingConvention.Cdecl)]
    public static int TestExport(int left, int right)
    {
        return left + right;
    }
}

然后您可以加载 dll 并在 Python 中调用公开的方法(适用于 2.7)

import ctypes
a = ctypes.cdll.LoadLibrary(source)
a.add(3, 5)

【讨论】:

  • 为什么从here复制答案?相反,您可以提供网址...
猜你喜欢
  • 2011-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多