-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Expand file tree
/
Copy pathctypes_cpp_test.py
More file actions
32 lines (25 loc) · 946 Bytes
/
ctypes_cpp_test.py
File metadata and controls
32 lines (25 loc) · 946 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/usr/bin/env python
"""Simple examples of calling C functions through ctypes module."""
import ctypes
import pathlib
import sys
if __name__ == "__main__":
libname = pathlib.Path().absolute()
print("libname: ", libname)
# Load the shared library into c types.
if sys.platform.startswith("win"):
c_lib = ctypes.CDLL(libname / "cppmult.dll")
else:
c_lib = ctypes.CDLL(libname / "libcppmult.so")
# Sample data for our call:
x, y = 6, 2.3
# This will not work:
# answer = c_lib.cmult(x, y)
# This produces a bad answer:
answer = c_lib.cppmult(x, ctypes.c_float(y))
print(f" In Python: int: {x} float {y:.1f} return val {answer:.1f}")
print()
# You need tell ctypes that the function returns a float
c_lib.cppmult.restype = ctypes.c_float
answer = c_lib.cppmult(x, ctypes.c_float(y))
print(f" In Python: int: {x} float {y:.1f} return val {answer:.1f}")