简体   繁体   中英

C# dll file function access from python code

My aim is to access C# dll file function from python script ctypes library. My C# code is:

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

}

and python code is :

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

But I am getting error AttributeError: function 'MyFunctionName' not found

How I can resolve the error as the I can't access the functions included in dll file ?

Maybe this helps. From RGiesecke.DllExport documentation: - You have to set your platform target to either x86, ia64 or x64. AnyCPU assemblies cannot export functions . - The export name defaults to the method name and the calling convention to stdcall. If that's all what you want, you can just use [DllExport] without parameters. - You cannot put your exports in generic types or export generic methods. (The CLR wouldn't know what type parameters to use)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM