1

I want to access a function my_function() present in a c# file which is compiled into a .net dll - abc.dll.

C# file

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;


            namespace Test
            {
                public class Class1
                {
                    public string my_function()
                    {
                        return "Hello World.. :-";
                    }
                }
            }

After compiling the above code to abc.dll

Using the below python trying to access my_function()

            import ctypes
            lib = ctypes.WinDLL('abc.dll')
            print lib.my_function()

Above code throws error

lib.my_function() Traceback (most recent call last): File "", line 1, in File "C:\Anaconda\lib\ctypes__init__.py", line 378, in getattr func = self.getitem(name) File "C:\Anaconda\lib\ctypes__init__.py", line 383, in getitem func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'my_function' not found

2
  • I'm guessing you should use the full function's namespace. Did you try print lib.Test.Class1.my_function() ? Commented Jul 25, 2016 at 13:47
  • You have to make your .net dll COM visible. Commented Jul 25, 2016 at 13:48

1 Answer 1

2

You haven't made the function visible in the DLL.

There are a few different ways you can do this. The easiest is probably to use the unmanagedexports package. It allows you to call C# functions directly like normal C functions by decorating your function with [DllExport] attribute, like P/Invoke's DllImport. It uses part of the subsystem meant to make C++/CLI mixed managed libraries work.

C# code

class Example
{
     [DllExport("ExampleFunction", CallingConvention = CallingConvention.StdCall)]
     public static int ExampleFunction(int a, int b)
     {
         return a + b;
     } 
}

Python

import ctypes
lib = ctypes.WinDLL('example.dll')
print lib.ExampleFunction(12, 34)
Sign up to request clarification or add additional context in comments.

4 Comments

Do I need to include and namespace for this, because even after including the DLLExport package getting error - The type or namespace name 'DLLExport' could not be found.
You'll need to install the Unmanaged Exports package, either from the website I linked, or by finding the NuGet package under 'Project', then 'Manage NuGet Packages...'
Its still showing the same error - AttributeError: function 'ExampleFunction' not found
Then you are doing something wrong. But that's now your problem to debug.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.