Why can't I destroy Py_Decref() the pointer? It crashes because of that. Anyone could point to me what is wrong in this piece of code?
Code:
#include "stdafx.h"
#include <windows.h>
#include <string>
#include <Python.h>
#include <iostream>
using namespace std;
#include "BounceInterface_wrap.cxx"
PyObject * pModule = NULL, *pFunc = NULL;
PyThreadState * mainThreadState = NULL;
const char * line = "from time import time,ctime\nprint 'Today is',ctime(time())\n";
DWORD WINAPI Callback1( LPVOID lpvData)
{
for(int i = 0; i < 200; i++)
{
PyObject *pArgs, *pObject, *pMsg;
BounceResult Object;
pObject = SWIG_NewPointerObj((void*)&Object, SWIGTYPE_p_BounceResult, 1);
pMsg = PyString_FromString("ASDASDSAD");
PyObject * pValue = NULL;
pArgs = PyTuple_New(2);
PyTuple_SetItem(pArgs, 0, pObject);
PyTuple_SetItem(pArgs, 1, pMsg);
if(pArgs && pMsg && pObject)
{
//printf("Calling function...");
Py_BEGIN_ALLOW_THREADS;
pValue = PyObject_CallFunction(pFunc, "O", pArgs);
Py_END_ALLOW_THREADS;
}
else
{
return NULL;
}
if (!pValue) {
fprintf(stderr, "Cannot convert argument\n");
return NULL;
}
if (pValue) {
Py_XDECREF(pValue);
}
else {
PyErr_Print();
fprintf(stderr,"Call failed\n");
return NULL;
}
if(pObject != NULL)
{
// Py_DECREF(pObject);; If I uncomment this it'll crash
}
if(pArgs != NULL)
{
// Py_DECREF(pArgs); If I uncomment this it'll crash
}
}
Sleep(100);
return TRUE;
};
int main(int argc, char *argv[])
{
Py_Initialize();
PyEval_InitThreads();
SWIG_init();
init_BounceCheck();
PyObject *pName = NULL;
pName = PyString_FromString("bounce");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL)
{
pFunc = PyObject_GetAttrString(pModule, "CheckBounce");
if (!pFunc || !PyCallable_Check(pFunc))
{
printf("ERROR\n");
//Py_DECREF(pFunc);
system("PAUSE");
}
}
const int nHandles = 1000;
HANDLE hHandles[nHandles];
DWORD threadID[nHandles];
for(int i = 0; i < nHandles; i++)
{
hHandles[i] = CreateThread(NULL,0 ,Callback1,(LPVOID)NULL,0,&threadID[i]);
}
cout << "Waiting for the threads to end" << endl;
for(int i = 0; i < nHandles; i++)
{
WaitForSingleObject(hHandles[i],INFINITE);
CloseHandle(hHandles[i]);
}
cout << "Threads are finished...\n";
// shut down the interpreter
Py_Finalize();
system("PAUSE");
return 0;
}