update
This commit is contained in:
9
2025.07.27_programming_with_python_and_c/example_1/a.py
Normal file
9
2025.07.27_programming_with_python_and_c/example_1/a.py
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
from ctypes import cdll
|
||||||
|
|
||||||
|
lib = cdll.LoadLibrary("libc.so.6") # Linux 系统
|
||||||
|
# lib = cdll.msvcrt # Windows 系统
|
||||||
|
|
||||||
|
# 调用 C 标准库中的 printf 函数,字符串需要编码为 bytes
|
||||||
|
message = b"Hello, ctypes!\n"
|
||||||
|
result = lib.printf(message)
|
||||||
|
print(result)
|
8
2025.07.27_programming_with_python_and_c/example_2/a.py
Normal file
8
2025.07.27_programming_with_python_and_c/example_2/a.py
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
from ctypes import cdll
|
||||||
|
|
||||||
|
lib = cdll.LoadLibrary('./example.so') # Linux 系统
|
||||||
|
# lib = cdll.LoadLibrary('./example.dll') # Windows 系统
|
||||||
|
|
||||||
|
# 调用 C 函数
|
||||||
|
result = lib.add_two_numbers(3, 5)
|
||||||
|
print(result)
|
@@ -0,0 +1,3 @@
|
|||||||
|
int add_two_numbers(int a, int b) {
|
||||||
|
return a + b;
|
||||||
|
}
|
4
2025.07.28_programming_with_python_and_cpp/a.py
Normal file
4
2025.07.28_programming_with_python_and_cpp/a.py
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
import example
|
||||||
|
|
||||||
|
print(example.hello())
|
||||||
|
print(example.add(3, 5))
|
12
2025.07.28_programming_with_python_and_cpp/example.cpp
Normal file
12
2025.07.28_programming_with_python_and_cpp/example.cpp
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
#include <pybind11/pybind11.h>
|
||||||
|
|
||||||
|
int add(int a, int b) {
|
||||||
|
return a + b;
|
||||||
|
}
|
||||||
|
|
||||||
|
PYBIND11_MODULE(example, m) {
|
||||||
|
m.def("add", &add, "A function that adds two numbers");
|
||||||
|
m.def("hello", []() {
|
||||||
|
return "Hello from C++!";
|
||||||
|
});
|
||||||
|
}
|
14
2025.07.28_programming_with_python_and_cpp/setup.py
Normal file
14
2025.07.28_programming_with_python_and_cpp/setup.py
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
from setuptools import setup, Extension
|
||||||
|
import pybind11
|
||||||
|
|
||||||
|
setup(
|
||||||
|
name='example',
|
||||||
|
ext_modules=[
|
||||||
|
Extension(
|
||||||
|
'example',
|
||||||
|
['example.cpp'],
|
||||||
|
include_dirs=[pybind11.get_include()],
|
||||||
|
language='c++',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
Reference in New Issue
Block a user