python嵌入c++

1.去主页下载源代码项目

2.编译下载下来的项目

3.新建项目填入下面代码

// pythonIncludeTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Python.h>

#pragma comment(lib, "python33.lib")
 #pragma warning(disable:4996)
int _tmain(int argc, _TCHAR* argv[])
{
    
    Py_SetProgramName(argv[0]);
    Py_SetPythonHome(L"G://SoftProject/cPython/pythonIncludeTest/Debug/");
    Py_InitializeEx(0);

    
    FILE * fp = NULL;
    fp = fopen("G://SoftProject/cPython/pythonIncludeTest/Debug/main.py", "r");

    if (fp == NULL) 
    {
            return 1;
    }
    PyRun_SimpleFile(fp, "main.py");

    //PyRun_SimpleString("import sys
"
    //                    "print(sys.getfilesystemencoding())
");
    Py_Finalize();
    scanf("exit");
    return 0;
}
View Code

4.添加包含目录和库目录(项目上右键,属性,配置属性,VC++目录)

包含目录指向源码的include目录,库目录指向PCbuild目录(要事先编译成功PCbuild目录就会有lib文件)

5.拷贝源码文件夹下的python33.dll(debug版是python33_d.dll)和Lib文件夹到当前目录,如果用到如ctypes等需要pyd的功能,还要编译该功能的对应项目,并拷贝相应的pyd文件到程序所在目录

python 会自动导入当先执行文件夹下的Lib文件夹下的文件,并且会根据模块如ctypes去当前文件夹找pyd文件如,ctypes_d.pyd

导入压缩版类库的代码版本:

// pythonIncludeTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Python.h>

#pragma comment(lib, "python33.lib")
 #pragma warning(disable:4996)
int _tmain(int argc, _TCHAR* argv[])
{
    
    Py_NoSiteFlag=1;
    Py_SetProgramName(argv[0]);
    Py_SetPythonHome(L"G://SoftProject/cPython/pythonIncludeTest/Debug/");
    Py_InitializeEx(0);

    char pycmd[1000]; // temporary buffer for forged Python script lines
    snprintf(
        pycmd,
        sizeof(pycmd),
        "import sys; sys.path = ['%s','%s/Lib']",
        "G://SoftProject/cPython/pythonIncludeTest/Debug",
        "G://SoftProject/cPython/pythonIncludeTest/Debug"
    );
    PyRun_SimpleString(pycmd);

    
    FILE * fp = NULL;
    fp = fopen("G://SoftProject/cPython/pythonIncludeTest/Debug/main.py", "r");

    if (fp == NULL) 
    {
            return 1;
    }
    PyRun_SimpleFile(fp, "main.py");

    //PyRun_SimpleString("import sys
"
    //                    "print(sys.getfilesystemencoding())
");
    Py_Finalize();
    scanf("exit");
    return 0;
}
View Code

怎么压缩所有源代码:http://docs.python.org/3.3/distutils/sourcedist.html

原文地址:https://www.cnblogs.com/wangjixianyun/p/3333311.html