【问题标题】:C# dll file function access from python code从 python 代码访问 C# dll 文件函数
【发布时间】:2017-09-19 10:32:06
【问题描述】:

我的目标是从 python 脚本 ctypes 库访问 C# dll 文件函数。 我的 C# 代码是:

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

    namespace ConsoleApp1
    {
       [ComVisible(true)]
       public class Program
      {
    [DllExport("MyFunctionName", CallingConvention = CallingConvention.Cdecl)]
    [return: MarshalAs(UnmanagedType.LPWStr)]
    public static string MyFunctionName([MarshalAs(UnmanagedType.LPWStr)] string iString)
    {
        return "hello world i'm " + iString;
    }

    [DllExport("Add",CallingConvention = CallingConvention.Cdecl)]
    public static int Add(int a, int b)
    {
        return a + b;
    }
    [DllExport(CallingConvention = CallingConvention.Cdecl)]
    static public int Subtract(int a, int b)
    {
        return a - b;
    }
    [DllExport(CallingConvention = CallingConvention.Cdecl)]
    static public int Multiply(int a, int b)
    {
        return a * b;
    }
    [DllExport(CallingConvention = CallingConvention.Cdecl)]
    static public int Divide(int a, int b)
    {
        return a / b;
    }

    static void Main(string[] args)
    {
        //Console.Write(Add(2,3));
    }
}

}

而python代码是:

    import ctypes
    a=ctypes.cdll.LoadLibrary('File Location')
    a.MyFunctionName("a")

但我收到错误 AttributeError: function 'MyFunctionName' not found

由于无法访问 dll 文件中包含的函数,我该如何解决该错误?

【问题讨论】:

    标签: c# python dll ctypes


    【解决方案1】:

    也许这会有所帮助。来自 RGiesecke.DllExport 文档: - 您必须将您的平台目标设置为 x86、ia64 或 x64。 AnyCPU 程序集无法导出函数。 - 导出名称默认为方法名称,调用约定默认为 stdcall。如果这就是您想要的,您可以使用不带参数的 [DllExport]。 - 您不能将您的导出放在泛型类型或导出泛型方法中。 (CLR 不知道使用什么类型参数)

    【讨论】:

    • 虽然我之前将解决方案平台设置为 x64,但仍然出现错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多