Windows系统 python调用c++以及c++调用python的详细示例代码
时间: 2023-07-29 22:14:55 浏览: 125
以下是一个简单的示例代码,演示如何在Windows系统上实现Python调用C++,以及C++调用Python。
Python调用C++的示例代码:
```python
# test.py
import ctypes
# 加载C++编译的DLL
mydll = ctypes.cdll.LoadLibrary("mydll.dll")
# 调用C++函数
result = mydll.add(1, 2)
print(result)
```
C++编写的DLL示例代码:
```cpp
// mydll.cpp
#include <iostream>
// 导出函数
extern "C" __declspec(dllexport) int add(int a, int b)
{
std::cout << "C++ function called." << std::endl;
return a + b;
}
```
使用Visual Studio编译上面的C++代码,生成DLL文件mydll.dll。
C++调用Python的示例代码:
```cpp
// test.cpp
#include <Python.h>
int main()
{
Py_Initialize();
// 导入Python模块
PyObject* pModule = PyImport_ImportModule("test");
if (!pModule)
{
std::cout << "Failed to import module." << std::endl;
return 0;
}
// 导入Python函数
PyObject* pFunc = PyObject_GetAttrString(pModule, "add");
if (!pFunc || !PyCallable_Check(pFunc))
{
std::cout << "Failed to import function." << std::endl;
return 0;
}
// 调用Python函数
PyObject* pArgs = PyTuple_New(2);
PyTuple_SetItem(pArgs, 0, PyLong_FromLong(1));
PyTuple_SetItem(pArgs, 1, PyLong_FromLong(2));
PyObject* pResult = PyObject_CallObject(pFunc, pArgs);
// 获取Python函数返回值
int result = PyLong_AsLong(pResult);
std::cout << "Python function called. Result: " << result << std::endl;
Py_Finalize();
return 0;
}
```
Python代码示例:
```python
# test.py
def add(a, b):
print("Python function called.")
return a + b
```
使用Visual Studio编译上面的C++代码,生成可执行文件test.exe。运行test.exe,即可看到Python函数被调用的结果。
需要注意的是,Python版本和C++编译器版本需要匹配,否则可能会出现兼容性问题。此外,在实际开发中,需要考虑更多的安全和稳定性问题,例如参数类型检查、异常处理等。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)