简体   繁体   中英

embedding python in c++

I created a VCL Application in c++, borland. 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). 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" . please help. I have never used Python before. 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 .

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()

I read in another site that Py_Finalize has some problems in specific cases such as threading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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