想在不安裝python的情況下調用它,網上說的方法都不太詳細,就連官方給的chm檔案也沒提及怎麼配置,摸索了下,找到了簡單調用的辦法。記錄下。
0.編譯條件
MSVS 2010 C++ console程式
Python 2.7
1.需要的檔案及檔案夾
include檔案夾
libs檔案夾
Lib檔案夾
Python27.dll檔案
上面前3個檔案夾可以從其他安裝好Python的根目錄裡取得,dll檔案從system檔案夾裡考出來。這裡打包提供下本站下載下傳
2.VC工程配置
- 建立控制台項目PyTest,解壓縮上面的檔案夾放在.h.cpp目錄處;
- 由于沒有Debug下的dll,這裡隻能配置release的工程;
工程-屬性-VC++ Directories-Include Directories添加$(ProjectDir)python27\include
工程-屬性-VC++ Directories-Library Directories添加$(ProjectDir)python27\libs
釋放Python27.dll到Release目錄
3. 添加代碼
// PyTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <direct.h>
#include <windows.h>
#include <string.h>
#include "python.h"
using namespace std;
int _tmain(int argc, char* argv[])
{
char buffer[MAX_PATH];
_getcwd(buffer, MAX_PATH);
cout<<buffer<<endl;
strncat_s(buffer,"\\Python27",);//Python子產品路徑
Py_SetPythonHome(buffer);
Py_SetProgramName(argv[]); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
Py_Finalize();
system("pause");
return ;
}