2

I created the MathFuncsDll.dll from MSDN DLL example and running the calling .cpp worked fine. Now, trying to load this in IPython with ctypes like

import ctypes
lib = ctypes.WinDLL('MathFuncsDll.dll')

being in the correct folder yields

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 28: ordinal not in range(128)

Similarly in Python shell this yields

WindowsError: [Error 193] %1 is not a valid Win32 application

What should I change? Hm, it might be Win 7 64bit vs. some 32bit dll or something right? I'll check later when I've time again.

Konsta
  • 347
  • 4
  • 18

1 Answers1

3

ctypes doesn't work with C++, which the MathFuncsDLL example is written in.

Instead, write in C, or at least export a "C" interface:

#ifdef __cplusplus
extern "C" {
#endif

__declspec(dllexport) double Add(double a, double b)
{
    return a + b;
}

#ifdef __cplusplus
}
#endif

Also note that the calling convention defaults to __cdecl, so use CDLL instead of WinDLL (which uses __stdcall calling convention):

>>> import ctypes
>>> dll=ctypes.CDLL('server')
>>> dll.Add.restype = ctypes.c_double
>>> dll.Add.argtypes = [ctypes.c_double,ctypes.c_double]
>>> dll.Add(1.5,2.7)
4.2
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Thank you, I didn't differentiate between C and C++ at all when trying to load a DLL. So C, C++ and C# have to be considered separately, as well as plain, .Net and maybe other flavors? That is ctypes for C, maybe Boost for C++ and pythonnet for .Net/C# DLLs, right? – Konsta Apr 17 '12 at 17:41
  • Yes, there are different solutions for each. FYI, on StackOverflow if an answer is useful to you, up vote and/or accept it as the answer to your question using the arrows/check on the left of the answer. – Mark Tolonen Apr 18 '12 at 14:17
  • Ah, thank you for all your advice; I didn't know how to acknowledge your answer. I couldn't vote it up, my reputation is too low. I assume I can only provide a C interface to a C++ DLL if I have the source code. Or is this also possible for 3rd party DLLs the source code of which I do not have access to? – Konsta Apr 18 '12 at 19:17
  • I've used SWIG to interface to a C++ DLL. It can get complicated for more than simple object interfaces, but is very powerful. It basically writes a C interface layer and a python proxy library that makes it look like C++ objects again. – Mark Tolonen Apr 19 '12 at 02:09