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.
Related
I have a command that displays Ncurses stuffs (initscr, printw, addch, ...). That's okay.
At the end (endwin), I want to "output" (std::cout << "some string") a string to be processed by other command (or maybe redirected to a stream).
I want to do something like this :
my-ncurse-command | any-other-command
my-ncurse-command > some-stream
Problem is : my ncurses display is captured by the pipe or the redirect, not only the final string.
Is there a way to allow that ?
Thanks.
Instead of initscr(), use newterm(). If you are already using newterm it's just a matter of supplying a different output stream than stdout.
initscr() is equivalent to:
#include <cstdlib>
WINDOW* myinitscr() {
newterm(getenv("TERM"), stdout, stdin);
return stdscr;
}
so
#include <cstdio>
#include <cstdlib>
std::FILE* cursesout{};
WINDOW* myinitscr() {
cursesout = std::fopen("/dev/tty", "w"); // open new stream to your terminal
if(cursesout) newterm(std::getenv("TERM"), cursesout, stdin);
return stdscr;
}
and after endwin():
std::fclose(cursesout);
Alternatively, use a smart pointer to not have to std::fclose the new output stream manually:
#include <cstdio>
#include <cstdlib>
#include <memory>
using FILE_ptr = std::unique_ptr<FILE, decltype(&std::fclose)>;
FILE_ptr cursesout{nullptr, nullptr};
WINDOW* myinitscr() {
cursesout = FILE_ptr(std::fopen("/dev/tty", "w"), &std::fclose);
if(cursesout) newterm(std::getenv("TERM"), cursesout.get(), stdin);
return stdscr;
}
A version not taking the address of a standard library function (which is strictly prohibited) could look like this:
#include <cstdio>
#include <cstdlib>
#include <memory>
using FILE_ptr = std::unique_ptr<FILE, void (*)(FILE*)>;
FILE_ptr cursesout{nullptr, nullptr};
WINDOW* myinitscr() {
cursesout = FILE_ptr(std::fopen("/dev/tty", "w"), [](FILE* fp) {
std::fclose(fp);
});
if(cursesout) newterm(std::getenv("TERM"), cursesout.get(), stdin);
return stdscr;
}
I'm trying to use public example of compiling and running function from llvm bitcode, but it doesn't work (I'm using the last version of llvm)
Here is my code
#pragma warning(disable : 4146)
#include <iostream>
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Verifier.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Analysis/BasicAliasAnalysis.h"
using namespace llvm;
int main(int argc, char* argv[]) {
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
InitializeNativeTargetAsmParser();
llvm::LLVMContext context;
std::unique_ptr<llvm::Module> m{ new llvm::Module {"test", context} };
Constant* init_value = ConstantInt::get(Type::getInt32Ty(context), APInt(32, 12));
GlobalVariable* bsp = new GlobalVariable(*m, Type::getInt32Ty(context), false, GlobalValue::ExternalLinkage, init_value, "bsp", 0/*, GlobalValue::GeneralDynamicTLSModel*/);
llvm::FunctionType* funcType = llvm::FunctionType::get(Type::getInt32Ty(context), {}, false);
llvm::Function* mainFunc = llvm::Function::Create(funcType, llvm::Function::ExternalLinkage, "main", m.get());
llvm::BasicBlock* bb = llvm::BasicBlock::Create(context, "entrypoint", mainFunc);
IRBuilder<> builder(bb);
builder.CreateRet(builder.CreateLoad(bsp));
std::string err;
llvm::EngineBuilder EB(std::move(m));
EB.setEngineKind(llvm::EngineKind::JIT).setErrorStr(&err);
llvm::ExecutionEngine* EE = EB.create();
if (!EE) {
std::cerr << "unable to create a jitter: " << err << "\n";
return 0;
}
EE->finalizeObject();
const auto fa = (int(*)())EE->getFunctionAddress("main");
printf("%d\n", fa());
system("pause");
}
I can compile and build but this error appears at startup
unable to create a jitter: JIT has not been linked in.
I looked on the internet to find a solution to this problem, it was said that the file MCJIT.h needed to be included, but the code shows that it is included. And it also crash me on end of the function. Like i can use this code in the other function, but it will trigger a Visual Studio breakpoint at the exit of the function
EDIT:
I tried calling the LLVMLinkInMCJIT() function, this gave no result and I saw the following in my binary.
00007FF7C0D1AA96 | FF15 FC961A00 | call qword ptr ds:[<&LLVMLinkInInterpreter>]
LLVMLinkInInterpreter function code
00007FF8BCB6EC30 | C2 0000 | ret 0x0
Look like I need to rebuild my llvm-c.dll, I'll try it and tell you what happens
I use chdir() to switch the directory, and then use execvp() to execute "java Main". I'm sure there is Main.class, but something went wrong. I want to know why.
#include <cstdio>
#include <unistd.h>
using namespace std;
int main(){
char buf[80];
getcwd(buf,sizeof(buf));
printf("current working directory: %s\n", buf);
chdir("/home/keane/Judge/temp");
getcwd(buf,sizeof(buf));
printf("current working directory: %s\n", buf);
char *array[3];
array[0] = "java";
array[1] = "Main";
array[2] = NULL;
execvp("java", array);
return 0;
}
the error is could not find the main class , and I can run java Main in that directory.
What drives me crazy is that I can't use system("java Main"), and the error is that Error: Could not find or load main class Main, and it's just like this on my computer
update:
#include <unistd.h>
#include <cstdlib>
int main(){
chdir("/home/keane/Judge/temp");
system("pwd");
system("ls");
system("java Main");
return 0;
}
the output on console is:
/home/keane/Judge/temp
1.out 3.out 5.out Main.class stdout_spj.txt
2.out 4.out ce.txt Main.java
Error: Could not find or load the main class Main
my final solution is to reboot the computer and add -cp . to the java command.
althought I don't why is necessary.
thanks everyone!
This works as intended on my system, maybe you need to add -cp . to your java call.
EDIT: to elaborate: -cp (for classpath) tells java where to look for user provided .class files. This does not necessarily include the current working directory by default.
The execution of execvp() is non-blocking and takes ownership of the caller, that means that when it starts if the program ends too quickly you will never be able to see the result, to solve this I use fork(). The wait is just to avoid using sleep as I used at the begining. Its all in c.
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char** argv){
char buf[80];
getcwd(buf,sizeof(buf));
printf("current working directory: %s\n", buf);
chdir("/home/");
getcwd(buf,sizeof(buf));
printf("current working directory: %s\n", buf);
char *array[3] = {"java", "Main", NULL};
if(fork() == 0) {
if(execvp("java", array) < 0) {
fprintf(stderr, "Error spawning command: %s\n", strerror(errno));
}
} else {
printf("Command spawned\n");
wait(NULL); // Wait to the forked process to end (avoid using sleep)
}
return 0;
}
I want to apologize for bad English.
In my system, the CD drive is occupied by another device and the program code does not work correctly, what should I use to open and close the DVD-RW drive?
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <shellapi.h>
#include <mmsystem.h>
using namespace std;
int main()
{
MCI_OPEN_PARMS OpenParm;
MCI_SET_PARMS SetParm;
MCIDEVICEID dID;
OpenParm.lpstrDeviceType=L"CDAudio";
mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE, (DWORD_PTR)&OpenParm);
dID = OpenParm.wDeviceID;
mciSendCommand(dID, MCI_SET, MCI_SET_DOOR_OPEN, (DWORD_PTR)&SetParm);
Sleep(3000);
mciSendCommand(dID, MCI_SET, MCI_SET_DOOR_CLOSED, (DWORD_PTR)&SetParm);
mciSendCommand(dID, MCI_CLOSE, MCI_NOTIFY, (DWORD_PTR)&SetParm);
return 0;
}
My System
What use instead CDAudio?
I looked around and I couldn't find the answer to how exactly to do this. I am trying to use Pantheios for logging and I want to write to an external file (otherwise whats the point). I am following one of the examples provided but It doesn't seem to be making the log file anywhere. Here is the code:
Edit: Also pantheios_be_file_setFilePath is returning -4 (PANTHEIOS_INIT_RC_UNSPECIFIED_FAILURE) so thats.....not helpful
#include "stdafx.h"
#include <pantheios/pantheios.hpp>
#include <pantheios/implicit_link/core.h>
#include <pantheios/implicit_link/fe.simple.h>
#include <pantheios/implicit_link/be.WindowsConsole.h>
#include <pantheios/implicit_link/be.file.h>
#include <pantheios/frontends/fe.simple.h>
#include <pantheios/backends/bec.file.h>
#include <pantheios/inserters/args.hpp>
PANTHEIOS_EXTERN_C const PAN_CHAR_T PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING("LogTest");
int _tmain(int argc, _TCHAR* argv[])
{
try
{
pantheios_be_file_setFilePath(PANTHEIOS_LITERAL_STRING("testlogforme.log"), PANTHEIOS_BE_FILE_F_TRUNCATE, PANTHEIOS_BE_FILE_F_TRUNCATE, PANTHEIOS_BEID_ALL);
pantheios::log(pantheios::debug, "Entering main(", pantheios::args(argc,argv, pantheios::args::arg0FileOnly), ")");
pantheios::log_DEBUG("debug yo");
pantheios::log_INFORMATIONAL("informational fyi");
pantheios::log_NOTICE("notice me!");
pantheios::log_WARNING("warning!!");
pantheios::log_ERROR("error omg");
pantheios::log_CRITICAL("critical!!!");
pantheios::log_ALERT("alert mang");
pantheios::log_EMERGENCY("EMERGENCY!!!!!");
pantheios_be_file_setFilePath(NULL, PANTHEIOS_BEID_ALL);
system("pause");
return EXIT_SUCCESS;
}
catch(std::bad_alloc&)
{
pantheios::log_ALERT("out of memory");
}
catch(std::exception& x)
{
pantheios::log_CRITICAL("Exception: ", x);
}
catch(...)
{
pantheios::puts(pantheios::emergency, "Unexpected unknown error");
}
return EXIT_FAILURE;
}
Maybe I'm not calling a method or maybe its not being saved to a good location?
It turns out that some of the examples out there for pantheios are incorrect. You DO need to call pantheios_init() even if you are in C++. Here Is the example I got to work after deleting all my code and implementing an example that works.
// Headers for main()
#include <pantheios/pantheios.hpp>
#include <pantheios/backends/bec.file.h>
// Headers for implicit linking
#include <pantheios/implicit_link/core.h>
#include <pantheios/implicit_link/fe.simple.h>
#include <pantheios/implicit_link/be.file.h>
PANTHEIOS_EXTERN_C const char PANTHEIOS_FE_PROCESS_IDENTITY[] = "testLOL";
int main()
{
if(pantheios::pantheios_init() < 0)
{
return 1;
}
pantheios::log_NOTICE("log-1"); // save until log file set
pantheios_be_file_setFilePath("mylogfile.log"); // sets log file; write "log-1" stmt
pantheios::log_NOTICE("log-2"); // write "log-2" stmt
pantheios_be_file_setFilePath(NULL); // close "mylogfile"
pantheios::log_NOTICE("log-3"); // save until log file set
pantheios_be_file_setFilePath("mylogfile2.log"); // sets log file; write "log-3" stmt
pantheios::log_NOTICE("log-4"); // write "log-4" stmt
//system("pause");
return 0;
} // closes "mylogfile2" during program closedown
I found the example on a different post on stack overflow but like I said, the built in examples do not work.