1. 创建win32 应用台程序
在vs2015下创建 win32 程序
2.属性配置
- 打开属性配置页: 项目(/项目右键)->属性
配置: Release 平台:x64 - 配置属性 --> 常规 --> 平台工具集 --> Visual Studio 2015- windows XP(v140_xp)
- 配置属性 --> 调试 --> 环境 --> 修改配置如下:
PATH=D:\software\Anaconda3.5.1\env\pyTorch;$(LocalDebuggerEnvironment)
此处的环境,选择使用的python版本对应的python.exe 所在的目录 - 配置属性 --> VC++目录 --> 包含目录–> 修改配置如下:
选择python环境对应的 include 文件夹 - 配置属性 --> VC++目录 --> 库目录–> 修改配置如下:
选择python环境对应的 libs 文件夹 - 配置属性 --> C/C++目录 --> 附加包含目录–> 修改配置如下:
选择使用的python 环境对应的include文件夹 - 配置属性 --> 链接器 --> 常规–>附加库目录–> 修改配置如下:
选择使用的python 环境对应的libs文件夹 - 配置属性 --> 链接器 --> 输入–>附加依赖项–> 修改配置如下:
选择使用的python 环境对应版本的python.lib文件,如我的是python37,则配置文件为: D:\software\Anaconda3.5.1\env\pyTorch\libs\python37.lib
3.编写c++代码
// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "Python.h"
#include <iostream>
int main()
{
// Initialize the Python interpreter.
// 此处的目录为python.exe 所在的目录
Py_SetPythonHome(L"D:/software/Anaconda3.5.1/envs/pyTorch");
Py_Initialize();
// Create some Python objects that will later be assigned values.
PyObject *pModule, *pDict, *pFunc_add, *pFunc_hello, *pArgs, *pValue;
// Import the file as a Python module.
// 此处‘Sample’ 为被调用的python文件的名称 Sample.py
pModule = PyImport_ImportModule("Sample");
//pModule = PyImport_ImportModule("MAIN");
// Create a dictionary for the contents of the module.
pDict = PyModule_GetDict(pModule);
// Get the add method from the dictionary.
// 此处为python文件中定义的方法
pFunc_add = PyDict_GetItemString(pDict, "add");
pFunc_hello = PyDict_GetItemString(pDict, "hello");
//pFunc_show = PyDict_GetItemString(pDict, "show_image");
// Create a Python tuple to hold the arguments to the method.
pArgs = PyTuple_New(2);
// Convert 2 to a Python integer.
pValue = PyLong_FromLong(2);
// Set the Python int as the first and second arguments to the method.
PyTuple_SetItem(pArgs, 0, pValue);
PyTuple_SetItem(pArgs, 1, pValue);
// Call the function with the arguments.
PyObject_CallObject(pFunc_hello, NULL);
PyObject* pResult = PyObject_CallObject(pFunc_add, pArgs);
// Print a message if calling the method failed.
if (pResult == NULL)
printf("Calling the add method failed.\n");
// Convert the result to a long from a Python object.
long result = PyLong_AsLong(pResult);
// Destroy the Python interpreter.
Py_Finalize();
// Print the result.
printf("Calling Python to find the sum of 2 and 2.\n");
printf("The result is %d.\n", result);
std::cin.ignore();
return 0;
}
4.被调用的python文件
def hello():
print("hello!")
def add(a,b):
hellowo()
return a+b
def hellowo():
print('hello world')
将该python文件放在 项目文件 根目录下的 x64/Release/文件夹中。
5. 配置项目管理器
运行模式选择 Release ,运行平台选择 x64
即可调用成功
6. 参考资料
喝水不忘挖井人,感谢感谢