I invoke LSCopyApplicationURLsForURL() using C++, but get a segment fault - c++

I want to write a C++ program to get associated applications which are suitable to open specified file. I find the LSCopyApplicationURLsForURL API, and create a command line C++ application by XCode.
But after running this program, I always get segment fault. XCode shows EXEC_BAD_ACCESS(code=1, address....) error.
I also tryied running it from sudo, but the same result. What is the problem?
The code:
#include <iostream>
#include <objc/objc.h>
#include <objc/objc-runtime.h>
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
using namespace std;
int main(int argc, const char * argv[]) {
auto url = CFURLRef("file:///Users/efan/src/a.cpp");
auto ret = LSCopyApplicationURLsForURL(url, kLSRolesAll);
cout << ret << endl;
return 0;
}

Try creating your CFURLRef using one of the proper CFURLCreate* methods. See "Creating a CFURL" here.
For example:
auto tempStringURL = CFStringCreateWithCString(nullptr, "/Users/efan/src/a.cpp", kCFStringEncodingUTF8);
auto url = CFURLCreateWithFileSystemPath(nullptr, tempStringURL, kCFURLPOSIXPathStyle, FALSE);
auto ret = LSCopyApplicationURLsForURL(url, kLSRolesAll);
You need to Release the "Created" variables to clean up memory.

Related

Using JIT in llvm (ExecutionEngine create error) C++

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

libgit2: git_clone() fails with a "failed to create ssl object" error

I'm trying to clone a git repository using libgit2's git_clone() function, however, when I call the function it returns -1, and using giterr_last() (I get "undefined reference" if I use git_error_latest(), not sure why) I get the error "failed to create ssl object".
I've looked into the source code for the relevant file, here, and it seems as though it fails on line 711, SSL_new(git__ssl_ctx).
Here's my code:
#include <string>
#include <git2/clone.h>
#include <git2/errors.h>
#include <git2/common.h>
#include <iostream>
int main() {
git_repository* pGitRepository = nullptr;
std::string url = "https://github.com/Newbie13XD/nashmap.git";
std::string path = "/home/neboula/CLionProjects/gut/foo";
const git_clone_options* options = nullptr;
if (git_clone(&pGitRepository, url.c_str(), path.c_str(), options) != 0) {
const git_error* error = giterr_last();
std::cout << error->message;
}
return 0;
}
I'm compiling with g++ (version: Red Hat 8.3.1-2) and libgit2 version 0.27.8.
I figured it out, you have to call git_libgit2_init() prior to using any other functions in libgit2. Adding this to the start of my program solved the issue.

qt memory issues with camerainfo and combobox.currentText()

I am trying to grab the names of webcams plugged into my computer and shove them into a combobox, then access the name later. Here is my code:
#include <QApplication>
#include <QComboBox>
#include <QCameraInfo>
#include <iostream>
int main(int argc, char *argv[])
{
QApplication app{ argc, argv };
QComboBox combo;
QList<QCameraInfo> info = QCameraInfo::availableCameras();
foreach(QCameraInfo i, info)
combo.addItem(i.description());
combo.show();
std::cout << combo.currentText().toStdString() << std::endl;
return app.exec();
}
The code creates and shows a combo box that has the name of a webcam that I have plugged in to the computer. It will then toss me an access violation exception in trying to print the combo box string to the console.
If I comment the cout line out, all is well, but on exit I get a Debug Assertion Failed! message:
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
which I take to mean I am deleting an object that has been deleted (the QString in the combobox???).
If I change the code to fill the combo box with dummies:
#include <QApplication>
#include <QComboBox>
#include <QCameraInfo>
#include <iostream>
int main(int argc, char *argv[])
{
QApplication app{ argc, argv };
for(int i=0; i<2; i++)
combo.addItem(QString("la la la");
combo.show();
std::cout << combo.currentText().toStdString() << std::endl;
return app.exec();
}
I get the same error on the cout, but if I comment that line out, the application exits correctly. I am using Visual Studio 2013, Windows 7, and Qt5.
Now it works. I kept the same source code, but completely scrapped the existing project and started a new one from scratch.
I've discovered that if I set the Runtime Library flag to Multi-Threaded DLL Debug, I will get access violation errors. If I set it to Multi-Threaded DLL, it is fine.
There may have been some other project settings that contributed, but this seems to be the main culprit.

Octave c++ and VS2010

I'm trying to Use Octave with Visual C++.
I have downloaded octave-3.6.1-vs2010-setup-1.exe. Created a new project, added octave include folder to include path, octinterp.lib and octave.lib to lib path, and I added Octave bin folder as running directory.
The program compiles and runs fine except feval function that causes the exception:
Microsoft C++ exception: octave_execution_exception at memory location 0x0012faef
and on Octave side:
Invalid resizing operation or ambiguous assignment to an out-of-bounds array element.
What am I doing wrong?
Code for a standalone program:
#include <octave/octave.h>
#include <octave/oct.h>
#include <octave/parse.h>
int main(int argc, char **argv)
{
if (octave_main (argc, argv, true))
{
ColumnVector NumRands(2);
NumRands(0) = 10;
NumRands(1) = 1;
octave_value_list f_arg, f_ret;
f_arg(0) = octave_value(NumRands);
f_ret = feval("rand",f_arg,1);
Matrix unis(f_ret(0).matrix_value());
}
else
{
error ("Octave interpreter initialization failed");
}
return 0;
}
Thanks in advance.
I tried it myself, and the problem seems to originate from the feval line.
Now I don't have an explanation as to why, but the problem was solved by simply switching to the "Release" configuration instead of the "Debug" configuration.
I am using the Octave3.6.1_vs2010 build, with VS2010 on WinXP.
Here is the code I tested:
#include <iostream>
#include <octave/oct.h>
#include <octave/octave.h>
#include <octave/parse.h>
int main(int argc, char **argv)
{
// Init Octave interpreter
if (!octave_main(argc, argv, true)) {
error("Octave interpreter initialization failed");
}
// x = rand(10,1)
ColumnVector sz(2);
sz(0) = 10; sz(1) = 1;
octave_value_list in = octave_value(sz);
octave_value_list out = feval("rand", in, 1);
// print random numbers
if (!error_state && out.length () > 0) {
Matrix x( out(0).matrix_value() );
std::cout << "x = \n" << x << std::endl;
}
return 0;
}
with an output:
x =
0.165897
0.0239711
0.957456
0.830028
0.859441
0.513797
0.870601
0.0643697
0.0605021
0.153486
I'd guess that its actually stopped pointing at the next line and the error actually lies at this line:
f_arg(0) = octave_value(NumRands);
You seem to be attempting to get a value (which value?) from a vector and then assigning it to element 0 of a vector that has not been defined as a vector.
I don't really know though ... I've never tried writing octave code like that. I'm just trying to work it out by translating the code to standard matlab/octave code and that line seems really odd to me ...

How to print unicode characters using Qt?

I'm trying to do something very simple, I just want to print my native language, pt-br in Windows Console.
IDE Creator
I created a new project->other->Qt Console Application the I put it in my main.cpp file:
#include <QCoreApplication>
#include <QDebug>
#include <QTextCodec>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug() << "aeiou áéíóú";
std::cout << "aeiou áéíóú" << endl;
return 0;
}
here is what I got:
C:\Users\maiko.costa\testeQtConsole\debug>testeQtConsole.exe
aeiou ßÚݾ·
aeiou ßÚݾ·
C:\Users\maiko.costa\testeQtConsole\debug>
I've tried it too, but with the same previous output:
#include <QCoreApplication>
#include <QDebug>
#include <QTextCodec>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTextCodec *codec = QTextCodec::codecForName("CP1252");
QTextCodec::setCodecForCStrings(codec);
qDebug() << "aeiou áéíóú";
std::cout << "aeiou áéíóú" << endl;
return 0;
}
The System encode for Windows 7 is it right ?
what am I missing ?
I am not that familiar with QT but I think this can help you just as well. The Windows console uses the OEM char set. Therefore, in order to properly print characters on std::cout they need to be encoded using OEM. This can be accomplished using the Windows API CharToOem.
Small example, just so you get the idea (here input is assumed to be UTF16):
void oemPrint(const wchar_t* str) {
char* chars = (char*)alloca(strlen(str)+1);
CharToOemW(str, chars);
fputs(chars, stdout);
}
// Usage:
oemPrint(L"aeiou áéíóú");
EDIT: A QT solution might be to use QTextCodec::codecForName("IBM 850") - this is the OEM codec.
I find the solution in this thread. Output unicode strings in Windows console app
If I ran chcp 65001 in windows console before I ran my app the characters are printed correctly.
I don't know how to workaround it in my source code, then I call this program manually with the start cpp function.
Here is the return line of function I wrote that displays passwords as ● ● ● ● ●
return QString::fromUtf8( "\u25CF \u25CF \u25CF \u25CF \u25CF" );
QString::fromUnicode should work the same.
Maybe something like:
QString x = QString::fromUtf8( "\u25CF \u25CF \u25CF \u25CF \u25CF" );
std::cout << qPrintable(x) << std::endl;
Of course change it to QString::fromUnicode... hope this helps
QString a="aeiou áéíóú";
std::cout<< a.toStdString().data();