File tree Expand file tree Collapse file tree 3 files changed +52
-3
lines changed
Expand file tree Collapse file tree 3 files changed +52
-3
lines changed Original file line number Diff line number Diff line change 1- float cppmult (int int_param, float float_param);
1+ #ifdef _MSC_VER
2+ #define EXPORT_SYMBOL __declspec (dllexport)
3+ #else
4+ #define EXPORT_SYMBOL
5+ #endif
6+
7+ #ifdef __cplusplus
8+ extern " C" {
9+ #endif
10+
11+ EXPORT_SYMBOL float cppmult (int int_param, float float_param);
12+
13+ #ifdef __cplusplus
14+ }
15+ #endif
Original file line number Diff line number Diff line change 22""" Simple examples of calling C functions through ctypes module. """
33import ctypes
44import sys
5+ import pathlib
56
67if __name__ == "__main__" :
8+ libname = pathlib .Path ().absolute ()
9+ print ('libname: ' , libname )
10+
711 # Load the shared library into c types.
812 if sys .platform .startswith ("win" ):
9- c_lib = ctypes .CDLL ("cmult.dll" )
13+ c_lib = ctypes .CDLL (libname / "cmult.dll" )
1014 else :
11- c_lib = ctypes .CDLL ("libcmult.so" )
15+ c_lib = ctypes .CDLL (libname / "libcmult.so" )
1216
1317 # Sample data for our call:
1418 x , y = 6 , 2.3
Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python
2+ """ Simple examples of calling C functions through ctypes module. """
3+ import ctypes
4+ import sys
5+ import pathlib
6+
7+ if __name__ == "__main__" :
8+ libname = pathlib .Path ().absolute ()
9+ print ('libname: ' , libname )
10+
11+ # Load the shared library into c types.
12+ if sys .platform .startswith ("win" ):
13+ c_lib = ctypes .CDLL (libname / "cppmult.dll" )
14+ else :
15+ c_lib = ctypes .CDLL (libname / "libcppmult.so" )
16+
17+ # Sample data for our call:
18+ x , y = 6 , 2.3
19+
20+ # This will not work:
21+ # answer = c_lib.cmult(x, y)
22+
23+ # This produces a bad answer:
24+ answer = c_lib .cppmult (x , ctypes .c_float (y ))
25+ print (f" In Python: int: { x } float { y :.1f} return val { answer :.1f} " )
26+ print ()
27+
28+ # You need tell ctypes that the function returns a float
29+ c_lib .cppmult .restype = ctypes .c_float
30+ answer = c_lib .cppmult (x , ctypes .c_float (y ))
31+ print (f" In Python: int: { x } float { y :.1f} return val { answer :.1f} " )
You can’t perform that action at this time.
0 commit comments