1) 新建一個 內嵌 Python 語句的 C 代碼,
// This is a test for check insert the Python statements or module in C. #include "Python.h" int main(void) { // execute python statements Py_Initialize(); PyRun_SimpleString("import os"); PyRun_SimpleString("print os.getcwd()"); Py_Finalize(); return 0; }
2) Visual Studio 2013 環境設置
右鍵單擊工程,選擇 Properties,
添加的 include 路徑,
復制重命名C盤 python27.lib 為 python27_d.lib
Linker 的 Input 添加上述 lib 的路徑,
因為當前使用 64 位 Python,故修改編譯平台為 x64,
continue,
之后編譯即可。
3) C 中嵌入使用 Python 模塊的語句,
當前工程目錄下建立一個 hello.py,
#!/usr/bin/env python # -*- coding: utf-8 -*- def sayHi(): print 'Hi, How are you?'
C 文件為,
// This is a test for check insert the Python statements or module in C. #include "Python.h" int main(void) { // execute python module Py_Initialize(); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('.')"); PyObject * pModule = NULL; PyObject * pFunc = NULL; pModule = PyImport_ImportModule("hello"); pFunc = PyObject_GetAttrString(pModule, "sayHi"); PyEval_CallObject(pFunc, NULL); Py_Finalize(); return 0; }
之后編譯即可。
一般情況下,用 C 擴展 Python 的情況居多,即把 C 代碼包裝成 Python 接口,在主 Python 程序中使用,可以提升程序運行效率或是為了利用已有的C代碼。
而將 Python 嵌入 C 一般是為了利用 Python 中現成的模塊或方法,比較少用。
更多內容請閱讀 Python 官方 Help 文檔。
完。