工程目录
PS C:\Users\PC\CLionProjects\my_add> tree /F
├─cmake-build-debug
│ ├─bin
│ │ libmy_add.dll
│ │ python_dll_tets.py
│ CMakeLists.txt
└─src│ main.cpp└─libmy_lib.cppmy_lib.h
main.cpp
#include "./lib/my_lib.h"
#include <iostream>
int main() {int result = add(2, 3); std::cout << "2 + 3 = " << result << std::endl;print_hello(); return 0;
}
lib/my_lib.h
#ifndef MY_LIB_H
#define MY_LIB_H
#ifdef _WIN32
#ifdef MY_LIB_EXPORTS
#define MY_LIB_API __declspec(dllexport)
#else
#define MY_LIB_API __declspec(dllimport)
#endif
#else
#define MY_LIB_API
#endif
#ifdef __cplusplus
extern "C" {
#endif
MY_LIB_API int __cdecl add(int a, int b);
MY_LIB_API void __cdecl print_hello();#ifdef __cplusplus
}
#endif#endif
lib/my_lib.cpp
#include "my_lib.h"
#include <iostream>int add(int a, int b) {return a + b;
}void print_hello() {std::cout << "Hello from dynamic library!" << std::endl;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
set(CON_IS_BUILD_DLL 1)
project(my_add)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(${CON_IS_BUILD_DLL})add_library(${PROJECT_NAME} SHAREDsrc/lib/my_lib.cppsrc/lib/my_lib.h )else ()add_executable(${PROJECT_NAME}src/lib/my_lib.hsrc/lib/my_lib.cppsrc/main.cpp
)
endif()
set_target_properties(${PROJECT_NAME} PROPERTIESLIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)
install(TARGETS ${PROJECT_NAME}LIBRARY DESTINATION src RUNTIME DESTINATION bin
)
install(FILES src/my_lib.h DESTINATION include)
python_dll_tets.py
import os
import ctypes
mingw_bin = r"D:\Program Files (x86)\Dev-Cpp\mingw64\bin"
os.environ["PATH"] = mingw_bin + ";" + os.environ["PATH"]
dll_path = os.path.join(os.path.dirname(__file__), "libmy_add.dll")
if not os.path.exists(dll_path):print(f"❌ DLL 文件不存在!实际路径:{dll_path}")
else:class MyAdd(object):def __init__(self, dll_path):try:self.dll = ctypes.CDLL(dll_path)self._init_functions()print("✅ DLL 加载成功!")except Exception as e:print(f"❌ 加载 DLL 失败: {e}")def _init_functions(self):self.add = self.dll.addself.add.argtypes = [ctypes.c_int, ctypes.c_int]self.add.restype = ctypes.c_intself.print_hello = self.dll.print_helloself.print_hello.argtypes = []self.print_hello.restype = Noneif __name__ == "__main__":my_add = MyAdd(dll_path)if hasattr(my_add, 'add'):print(f"2 + 3 = {my_add.add(2, 3)}")if hasattr(my_add, 'print_hello'):my_add.print_hello()
✅ DLL 加载成功!
2 + 3 = 5
Hello from dynamic library!