4

i've got a third party c# dll which has been created in dot net 4.5 and has a platform target of x86. I would like to import this into a python script and I've started off with Rob Deary's answer here. However I can't get his example to work. I'm using python version 2.7.6 and I get an AttributeError as shown below.

File "C:\Python27\Lib\ctypes\__init__.py", line 378, in __getattr__
    func = self.__getitem__(name)
File "C:\Python27\Lib\ctypes\__init__.py", line 383, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'add' not found

Please note that I am aware of Ironpython and Python for dot net but I need to get this working specifically with C python. Here's my sample code which generates the custom c# library: ClassLibrary1.dll

using System;
using System.Runtime.InteropServices;
using RGiesecke.DllExport;

class Test
{
    [DllExport("add", CallingConvention = CallingConvention.Cdecl)]
    public static int TestExport(int a, int b)
    {
        return a + b;
    }
}

And here's the python script that generates the error

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

When I use the line below, this is the output i get. So at least I know that it is loading the dll, but i'm not sure why the function can't be found.

>>> lib.__dict__
{'_FuncPtr': <class 'ctypes._FuncPtr'>, '_handle': 254476288, '_name': 'ClassLibrary1.dll'}
>>>

Any help will be appreciated. Thanks

Community
  • 1
  • 1
BeeLabeille
  • 174
  • 1
  • 4
  • 16
  • you are passing python types instead of c_types to your lib function loaded in python using ctypes. try `lib.add(c_int(3),c_int(5))` – denfromufa Dec 14 '15 at 06:42

1 Answers1

0

As the RGiesecke.DllExport documentation states, you need to target a specific architecture (x86 or x64) when building your code. Leaving it set to Any CPU (the default) will not work.

Sparafusile
  • 4,696
  • 7
  • 34
  • 57
  • if you re-read my question you'll see that the platform target is already specified to x86 – BeeLabeille Sep 28 '16 at 21:51
  • You mentioned that a third party DLL was compiled for x86, but not if your own code was. Is the third party DLL using the DllExport attribute too? I guess I'm just confused why you start talking about a third party DLL, but then show your own code that doesn't use that DLL at all. Your code is correct and should work so it must be something you're not showing. – Sparafusile Sep 29 '16 at 17:10