C#dll文件函数从python代码访问

时间:2017-09-19 10:32:07

标签: c# python dll ctypes

我的目标是从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:找不到函数'MyFunctionName'

如何解决错误,因为我无法访问dll文件中包含的功能?

1 个答案:

答案 0 :(得分:0)

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

相关问题