简体   繁体   English

在c ++中嵌入python

[英]embedding python in c++

I created a VCL Application in c++, borland. 我用c ++,borland创建了一个VCL应用程序。 In my project there is a file where I have implemented embedded python in the methods defined in the same(my application contains a button which calls the method in which embedded python is implemented). 在我的项目中有一个文件,我在同一个方法中定义的方法中实现了嵌入式python(我的应用程序包含一个调用嵌入式python实现的方法的按钮)。 when I compile, my build is successful. 当我编译时,我的构建成功。 but when I run my application, and click on the button it shows the run time error : "Access violation at address 1E091375 in module 'PYTHON25.DLL'. Read of address 00000004" . 但是当我运行我的应用程序,然后单击按钮时,它会显示运行时错误:“模块'PYTHON25.DLL'中地址1E091375处的访问冲突。读取地址00000004”。 please help. 请帮忙。 I have never used Python before. 我之前从未使用过Python。 my program: 我的节目:

#pragma hdrstop

#include <fstream>
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>


#include "Python.h"

#include "Unit1.h"
#include "Unit2.h"
#pragma link "python25_bcpp.lib"

//---------------------------------------------------------------------------

#pragma package(smart_init)

bool callHelloWorld(int intVal)
{
    char fName[] = "Hello"; //file name
    char cFunc[] = "hello"; //method name

    char *pfName, *pcFunc;

    PyObject *pName, *pModule, *pDict, *pFunc ;

    pfName = fName;
    pcFunc = cFunc;

    Py_Initialize();

    pName = PyString_FromString(pfName);

    pModule = PyImport_Import(pName);

    pDict = PyModule_GetDict(pModule);

    pFunc = PyDict_GetItemString(pDict, pcFunc);

    if (PyCallable_Check(pFunc))
    {
        PyObject_CallObject(pFunc, NULL);
    } else
    {
        PyErr_Print();
    }


    // Py_DECREF(pModule);
    // Py_DECREF(pName);

    Py_Finalize();

    return 0;
}

Check the return values of PyImport_Import (is the module in the search path?) and PyDict_GetItemString . 检查PyImport_Import (是搜索路径中的模块?)和PyDict_GetItemString的返回值。

If that doesn't help put some trace messages in your app to see where it crashes. 如果这无助于在您的应用中添加一些跟踪消息,以查看它崩溃的位置。

This works for me: 这对我有用:

Just delete Py_Finalize() 只需删除Py_Finalize()

I read in another site that Py_Finalize has some problems in specific cases such as threading. 我在另一个网站上读到Py_Finalize在特定情况下遇到一些问题,比如线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM