c# - dll 未在 python 中加载

标签 c# python

所以我正在遵循这个问题中发布的解决方案

Calling a C# library from python

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;
    }
}

Python

import ctypes
a = ctypes.cdll.LoadLibrary('ClassLibrary1.dll')
a.add(3, 5)

错误

AttributeError: function 'add' not found

我所做的是将 dll 复制到桌面上,然后在桌面上运行 python shell,然后在 python shell 中运行以下几行。难道我做错了什么?

我使用的是Python 2.7

最佳答案

当尝试重现此问题时,得到了相同的行为。但原因非常简单 - 很可能您的 .NET 项目(就像我的一样)正在针对 AnyCPU。由于我们正在尝试创建非托管导出 - 我们需要针对 x86 和 x64 的单独版本。因此,要解决您的问题 - 例如,只需将 .NET 程序集定位为 x86。以下是我发现的方法(此信息也可能有用):在 Visual Studio 中,转到“工具”>“选项”>“项目和解决方案”>“生成并运行”。在那里您将看到 MSBuild 输出详细级别 - 将其设置为诊断。然后构建您的项目以及您将看到的其他内容:

Skipped method exports, because the platform target is neither x86 nor x64. Set the MsBuild property 'NoDllExportsForAnyCpu' to false if you want to create separate versions for x86 and x64. (e.g. you can do that in the package manager console: Set-NoDllExportsForAnyCpu -value $false) (TaskId:35)

关于c# - dll 未在 python 中加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32604078/

相关文章:

python - 使用 pyspark UDF 替换电话号码中的字符

python - 如何对凹面多边形进行三角剖分?

python - Matplotlib 中的\overline{} 不工作

c# - 在异步 BeginExecuteReader 中检测命令取消

c# - 重新附加实体图并检测集合更改

c# - 在一个 LINQ 查询中使用最近邻算法解决旅行商问题?

python - SMOTE后保留pandas数据帧结构,在python中过采样

Python:如何从列表中删除价低于特定值的值

c# - 将字符串解析为对象 C#

c# - 循环未完成