切换主题
使用C++调用Python开发的DLL
本文档介绍如何在C++项目中调用由Python开发的DLL文件。
前置条件
- 确保已安装以下工具:
- Visual Studio(支持C++开发)
- Python(与DLL兼容的版本)
- 已有一个由Python开发并通过工具生成的DLL文件。
Python DLL开发注意事项
- 使用
ctypes
或cffi
模块导出函数。 - 如果需要生成DLL,可以使用
pyinstaller
或其他工具:bashpyinstaller --onefile --dll YourPythonScript.py
1
在C++中调用Python DLL的步骤
1. 引入必要的头文件
在C++项目中,使用以下头文件:
cpp
#include <windows.h>
1
2. 加载DLL
使用LoadLibrary
函数加载DLL:
cpp
HINSTANCE hDll = LoadLibrary(L"YourPythonLibrary.dll");
if (!hDll) {
// 错误处理
return -1;
}
1
2
3
4
5
2
3
4
5
3. 获取函数指针
使用GetProcAddress
获取导出函数的地址:
cpp
typedef int (*YourFunctionType)(int, int);
YourFunctionType YourFunction = (YourFunctionType)GetProcAddress(hDll, "YourFunctionName");
if (!YourFunction) {
// 错误处理
FreeLibrary(hDll);
return -1;
}
1
2
3
4
5
6
7
2
3
4
5
6
7
4. 调用函数
调用获取的函数指针:
cpp
int result = YourFunction(10, 20);
1
5. 释放DLL
使用FreeLibrary
释放DLL:
cpp
FreeLibrary(hDll);
1
示例代码
以下是完整的示例代码:
cpp
#include <windows.h>
#include <iostream>
typedef int (*AddFunction)(int, int);
int main() {
HINSTANCE hDll = LoadLibrary(L"YourPythonLibrary.dll");
if (!hDll) {
std::cerr << "Failed to load DLL." << std::endl;
return -1;
}
AddFunction Add = (AddFunction)GetProcAddress(hDll, "Add");
if (!Add) {
std::cerr << "Failed to find function." << std::endl;
FreeLibrary(hDll);
return -1;
}
int result = Add(10, 20);
std::cout << "Result: " << result << std::endl;
FreeLibrary(hDll);
return 0;
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
注意事项
- 确保DLL文件与C++项目在同一目录,或将DLL路径添加到系统环境变量。
- 检查函数签名是否匹配,避免调用失败。
- 如果DLL依赖Python运行时,需确保运行环境中已安装对应版本的Python。