Search code examples
pythondllctypesdllexport

Strange function result when accessing a DLL via ctypes?


I'm trying to access some C code via Python using ctypes, so I wrote a very basic DLL (as follows), but get a very strange result when loading the DLL and calling the function.

Here's the C code, which I compiled as a DLL using Open Watcom. Nothing fancy as you can see:

#include <stdio.h>

__declspec(dllexport) int sum(int a, int b) {
    return (a + b);
}

Here's the output when I invoke the DLL function (the Watcom compiler adds an _ to the name of each export. Don't ask...):

Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> from ctypes import cdll
>>> mydll = cdll.LoadLibrary('c:\\dev\\C\\TestDLL\\test.dll')
>>> mydll
<CDLL 'c:\dev\C\TestDLL\test.dll', handle 1cb0000 at 1910a30>
>>> mydll.sum_(8,3)
4451768
>>> 

I get the SAME output no matter what parameters are passed to the function...

I would appreciate some kind soul pointing out the error of my ways and putting me out of my misery. :-)

Thanks in advance,

James


Solution

  • Try specify the cdecl calling convention. Works for me:

    #include <stdio.h>
    __declspec(dllexport) int __cdecl sum(int a, int b) { return (a + b); }
    
    
    import ctypes
    ctypes.CDLL('test.dll')._sum(8,3)