Calling c function from python will not work

I'm pretty sure I did it once a year ago ... It just didn't work. Weird I have to make a little mistake somewhere ... Please help!

I have the following code for c toys:

// testdll.c
int sum(int a, int b)
{
    return(a+b);
}

And then, since I use Windows 7, I used the WinSDK 7.1 x64 C / C ++ compiler to compile it:

cl testdll.c /TC /LD

The output is testdll.dll.

Then in my Python 3.3 I used:

In [12]: import ctypes

In [13]: lib = ctypes.cdll.LoadLibrary('./testdll.dll')

In [14]: lib
Out[14]: <CDLL './testdll.dll', handle f7000000 at a43ea58>

In [15]: lib.sum
Traceback (most recent call last):

  File "<ipython-input-15-309017dbbec8>", line 1, in <module>
    lib.sum

  File "C:\WinPython2\python-2.7.6.amd64\lib\ctypes\__init__.py", line 378, in __getattr__
    func = self.__getitem__(name)

  File "C:\WinPython2\python-2.7.6.amd64\lib\ctypes\__init__.py", line 383, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))

AttributeError: function 'sum' not found

He can not find this feature! It drives me crazy. Since I used pure C, and I used / TC at compile time, this should not be a name change problem.

Any idea would be appreciated. Thank you very much!

EDIT 2014/02/13 gcc, . . dir() python , - , , fun.sum. , int.

In [34]: dir(lib)
Out[34]: 
['_FuncPtr',
 '__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattr__',
 '__getattribute__',
 '__getitem__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_func_flags_',
 '_func_restype_',
 '_handle',
 '_name']

In [35]: lib._func_restype_
Out[35]: ctypes.c_long
+3
1

- :

 
cl testdll.c /LD /link /export:sum

. __declspec(dllexport) . . DLL Visual Studio.

:

 
#ifdef BUILD_TESTDLL
#define TESTAPI __declspec(dllexport)
#else
#define TESTAPI __declspec(dllimport)
#endif

/* declaration */
TESTAPI int sum(int a, int b);

/* definition */
int sum(int a, int b)
{
    return(a+b);
}

import lib __declspec(dllimport), TESTAPI. DLL BUILD_TESTDLL /D.

, .def, :

 
LIBRARY TESTDLL
EXPORTS
    sum @ 10 NONAME 
    sum_alias=sum @ 20

. :

cl testdll.c testdll.def /LD

Python, :

 
>>> from ctypes import *
>>> lib = cdll.testdll
>>> lib.sum_alias(1, 2)
3
>>> lib[10](1, 2)      
3
>>> lib[20](1, 2)
3

, ctypes DLL. dir(lib) . :

>>> from ctypes import *
>>> lib = cdll.testdll
>>> sorted(vars(lib))
['_FuncPtr', '_handle', '_name']
>>> lib.sum_alias(1, 2)
3
>>> sorted(vars(lib))
['_FuncPtr', '_handle', '_name', 'sum_alias']
+3

All Articles