Skip to content

Commit 684c1d7

Browse files
committed
add C++ examples for ctypes
1 parent 0bb85eb commit 684c1d7

File tree

3 files changed

+52
-3
lines changed

3 files changed

+52
-3
lines changed

python-bindings/cppmult.hpp

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,15 @@
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
Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,17 @@
22
""" Simple examples of calling C functions through ctypes module. """
33
import ctypes
44
import sys
5+
import pathlib
56

67
if __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

python-bindings/ctypes_cpp_test.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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}")

0 commit comments

Comments
 (0)