I've added a C++ file to my project written in Swift. It only calculates some random numbers and also uses an vector array. It's wrapper is written in Objective-C. When I try to call functions from the cpp file the App crashes after some time. But there's a strange behavior, because it doesn't crash while executing the C++ code (it runs like I expect to), but when I load a navigation controller. This hasn't to do anything with either. The console shows this:
'pthread_mutex_lock(&mutex)' failed with error 'EINVAL'(22)
I googled this bug, but I don't really understand the problem in my case.
Because you're using threaded code - the pthreads - the "crashes after some time" makes sense. I suspect it IS running the C++ code: your Swift code calls some Objective-C++ wrapper code, which calls some C++, which spawns a thread, and then returns back to you and you get the data at a later time somehow.
If I were you I'd look at the C++ threading code. There's a Stackoverflow answer that might be relevant here: EINVAL on pthread_mutex. Maybe there's a bug, or the C++ code fails because it assumes Linux and you're on macOS, or something.
I also almost hate to suggest this, but depending on the size/complexity of the C++ maybe it makes sense to just rewrite it in Swift. You're going through a lot of bridging layers to call this code, feels like it could be kind of fragile (which may explain what you're seeing).
(OR compile the C++ as a separate helper app and use cross-communication like XPC or just NSTask to talk back and forth from your C++ process to your Swift process)
Related
I need to define functions in c++ code to be user defined. Basically that he writes the function in form of a string which is exact c++ code, then use that function in the very next line of code.
I have tried to append output to a file which is imported, but it obviously failed
You simply cannot do it. C++ code can not be interpreted at run-time. You may want to try Qt/QML which will give an opportunity to run a javascript code or an entire QML file from network/string or any other method which can deliver your code to the host application.
I assume you are talking about a pure function such as a mathematical formula.
To my knowledge, what you ask is not possible without
a) writing your own parser, that effectively creates functions from strings or
b) using external libraries - a quick google search brought be to this library that seems to provide the functionality you are looking for. I have no personal experience with it, though.
As #Useless pointed out, "editing" the code after compilation is not intended in a compiled language as c++. This could be tricked by having a second code compiled and executed in the background; this, however, seems rather unelegant and would rely on additional threads, compilers and the operating system.
I need to provide my users the ability to write mathematical computations into the program. I plan to have a simple text interface with a few buttons including those to validate the script grammar, save etc.
Here's where it gets interesting. These functions the user is writing need to execute at multi-megabyte line speeds in a communications application. So I need the speed of a compiled language, but the usage of a script. A fully interpreted language just won't cut it.
My idea is to precompile the saved user modules into objects at initialization of the C++ application. I could then use these objects to execute the code when called upon. Here are the workflows I have in mind:
1) Testing(initial writing) of script: Write code in editor, save, compile into object (testing grammar), run with test I/O, Edit Code
2) Use of Code (Normal operation of application): Load script from file, compile script into object, Run object code, Run object code, Run object code, etc.
I've looked into several off the shelf interpreters, but can't find what I'm looking for. I considered JAVA, as it is pretty fast, but I would need to load the JAVA virtual machine, which means passing objects between C and the virtual machine... The interface is the bottleneck here. I really need to create a native C++ object running C++ code if possible. I also need to be able to run the code on multiple processors effectively in a controlled manner.
I'm not looking for the whole explanation on how to pull this off, as I can do my own research. I've been stalled for a couple days here now, however, and I really need a place to start looking.
As a last resort, I will create my own scripting language to fulfill the need, but that seems a waste with all the great interpreters out there. I've also considered taking an existing open source complier and slicing it up for the functionality I need... just not saving the compiled results to disk... I don't know. I would prefer to use a mainline language if possible... but that's not required.
Any help would be appreciated. I know this is not your run of the mill idea I have here, but someone has to have done it before.
Thanks!
P.S.
One thought that just occurred to me while writing this was this: what about using a true C compiler to create object code, save it to disk as a dll library, then reload and run it inside "my" code? Can you do that with MS Visual Studio? I need to look at the licensing of the compiler... how to reload the library dynamically while the main application continues to run... hmmmmm I could then just group the "functions" created by the user into library groups. Ok that's enough of this particular brain dump...
A possible solution could be use gcc (MingW since you are on windows) and build a DLL out of your user defined code. The DLL should export just one function. You can use the win32 API to handle the DLL (LoadLibrary/GetProcAddress etc.) At the end of this job you have a C style function pointer. The problem now are arguments. If your computation has just one parameter you can fo a cast to double (*funct)(double), but if you have many parameters you need to match them.
I think I've found a way to do this using standard C.
1) Standard C needs to be used because when it is compiled into a dll, the resulting interface is cross compatible with multiple compilers. I plan to do my primary development with MS Visual Studio and compile objects in my application using gcc (windows version)
2) I will expose certain variables to the user (inputs and outputs) and standardize them across units. This allows multiple units to be developed with the same interface.
3) The user will only create the inside of the function using standard C syntax and grammar. I will then wrap that function with text to fully define the function and it's environment (remember those variables I intend to expose?) I can also group multiple functions under a single executable unit (dll) using name parameters.
4) When the user wishes to test their function, I dump the dll from memory, compile their code with my wrappers in gcc, and then reload the dll into memory and run it. I would let them define inputs and outputs for testing.
5) Once the test/create step was complete, I have a compiled library created which can be loaded at run time and handled via pointers. The inputs and outputs would be standardized, so I would always know what my I/O was.
6) The only problem with standardized I/O is that some of the inputs and outputs are likely to not be used. I need to see if I can put default values in or something.
So, to sum up:
Think of an app with a text box and a few buttons. You are told that your inputs are named A, B, and C and that your outputs are X, Y, and Z of specified types. You then write a function using standard C code, and with functions from the specified libraries (I'm thinking math etc.)
So now your done... you see a few boxes below to define your input. You fill them in and hit the TEST button. This would wrap your code in a function context, dump the existing dll from memory (if it exists) and compile your code along with any other functions in the same group (another parameter you could define, basically just a name to the user.) It then runs the function using a functional pointer, using the inputs defined in the UI. The outputs are sent to the user so they can determine if their function works. If there are any compilation errors, that would also be outputted to the user.
Now it's time to run for real. Of course I kept track of what functions are where, so I dynamically open the dll, and load all the functions into memory with functional pointers. I start shoving data into one side and the functions give me the answers I need. There would be some overhead to track I/O and to make sure the functions are called in the right order, but the execution would be at compiled machine code speeds... which is my primary requirement.
Now... I have explained what I think will work in two different ways. Can you think of anything that would keep this from working, or perhaps any advice/gotchas/lessons learned that would help me out? Anything from the type of interface to tips on dynamically loading dll's in this manner to using the gcc compiler this way... etc would be most helpful.
Thanks!
I'm using xcode 6 to code up a C++ file-based array list (vector) for my Data abstractions course. This, of course, requires writing out binary files. I'm using the C-library functions (fopen, fclose,fread,fwrite,fseek, etc.) since I like those more than the C++ functions. I'm having no issues with my code per se. Everything's working fine, but the issue comes when I execute.
Xcode will "run" everything, but it won't give me out a binary file. I think this has something to do with xcode itself not writing out these files since, all in all, it's a pretty costly thing to do. I can do it through the terminal using g++ but it would be a lot easier if I could do it through the xcode compiler so I'm not having to switch to a terminal window every time to test my code. Let me know if you need any clarification and thanks so much in advance.
The issue might be your working directory not being set correctly inside Xcode.
The file is probably getting written, just not to the right place (or the place you expect it).
I have the source code to a relatively complex C++ application that involves lots of libraries, dependencies, etc. I am trying to take it and add a Cocoa GUI to it. I have failed so far at the following :
Create a new Cocoa xcodeproj and try to move all the libraries, etc. into the Cocoa app. I just can't get it to build. Thousands of errors no matter what I do. My skill here is just not good enough to figure out what's going on.
So, I am thinking that an easier method must be to make the appropriate changes to the C++ xcodeproj in order to make the main() function launch an NSApplication instead of whatever it is doing right now.
Does anyone know what I would have to do, precisely, to make this happen? I am new to Cocoa so I am unsure of what I would have to add. For reference, the main.cpp of the C++ app is actually really simple:
int main() {
ofSetupOpenGL(320,300, OF_WINDOW);
ofRunApp(new testApp());
}
What I'd like to do is make all the right changes so this can be:
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[]) {
return NSApplicationMain(argc, (const char **) argv);
}
And have the old xcodeproj compile with all the "stuff" still in it, and then when it is run, open up the Cocoa window.
It should be noted that the C++ xcodeproj appears to have absolutely nothing Cocoa-related, or even Objective-C related in it, so we'll have to add everything that is relevant and make all relevant changes.
Any ideas?
(Or, alternatively, if you know how I might easily get all the stuff from the C++ xcodeproj to build in a squeaky clean Cocoa xcodeproj, let me know, but this seems more complex to me at the moment.)
Thanks!
Well, I have two ideas...
Do You really need Cocoa? Mac support could be added with QT, wxWidgets and others.
You don't have to transfer every C++ line to Objective-C++. Objective-C++ can easily handle C++ code, You just have to change .cpp -> .mm and, of course, re-write some code relative to the UI. I think, the best way here is to create a blank Cocoa app from XCode and fill it with the old code step-by-step. First get You OpenGL stuff working with Cocoa app, than transfer C++ code renaming the files.
Hint:
You can cover some part of Your code with "blank declarations", i.e. define an empty macross instead of real function, put some blank classes with an empty methods if they are really necessary. Getting all the stuff compiling is the first and big step here. When everything compiles - put another part of the real code into the project and fix it to compile.
Unfortunately, I don't know better solution. I have re-factored huge projects few times and every time, on every platform and programming language(s) the recipe was the same. Good luck!
chances are, this will not go smoothly if you don't know c++ or similarly, cocoa.
otherwise, most of the transition will be monotonous, if you do know what you're doing. otherwise, prepare to learn a few things about objc.
first: don't bother converting a functioning c++ program's implementation to objc. it's a huge waste of time. you just wrap, bind, and alter the program to operate in that context. you don't have to write everything in objc.
second: you'll have to write some objc bindings/wrappers to use the c++ program. you'll have some wrapping to do, particularly for the ui elements and user events.
third: sources should compile as-is. you just add them to your new cocoa template project and gcc will compile it as a cpp file by default if it has the a recognized c++ extension. to use c++ and objc, use objc++ FILENAME.mm (you could also use .M, but that is not supported as well). even better, put the original cpp sources in a separate library, which the app links to.
fourth: now that you have a cocoa project template and compiling cpp sources, add the wrappers/bindings so the cocoa events/drawing performs in that context. based on your example code, your starting point uses Open GL so you'll have to use something like an NSOpenGLView if you want a Cocoa app. what exactly you'll need to implement depends on the project.
your main function should call NSApplicationMain, then your initial entries for writing the bindings to the c++ code will likely be event handling, NSWindow, NSView, and maybe NSApplication.
if you're new to objc, you'll probably have a bit of ramp-up.
I am writing a similar application but as I intend for it to be cross platform (Mac primarily and then Windows) I am keeping the backend deliberately as a C++ library. I will then provide whatever frontend GUI is appropriate (Cocoa on Mac and MFC on Windows). There is no conversion to do - you simply need to integrate what you already have.
Even though it's an old post, I didn't see this answer yet.
Your code
int main() {
ofSetupOpenGL(320,300, OF_WINDOW);
ofRunApp(new testApp());
}
Looks like Open Frameworks code. Why don't you download the Open Frameworks Mac XCode edition here, and try to put your sources in one of their example projects. For example the OpenGL flockingExample?
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Have you used any of the C++ interpreters (not compilers)?
Hi,
I am currently learning C++ and a beginner in programming in general. I've been trying to write some code to a few programming problems from the book I'm using. What I find is that often I make mistakes in what I write and those mistakes come up when the program is run. Its usually quite obvious where in the program I've gone wrong when there is regular output. But in a long computation I'm often not sure why a particular code has acted a certain way. I've also looked at Python recently. Python works with an interpreter, which can take any piece of Python code and compute its output.
I was wondering if there was something similar for C++. Right now when I want to check a line or block of code I have to comment out a lot, save it, compile it, and then run it from a command line. And I have to do that many times for a single error until I've solved it. Is there a way to type code into an active terminal which would run code and show me output? What would be better still would be a way to select a block of code (like you select text) or multiple blocks (to see how a function is being handled) within the IDE and click run to run just that block of code and see its output without having comment out irrelevant lines or to save the file. The compiled code could just reside in memory.
CINT is a c & C++ interpretter that accepts nearly all valid C++. Unfortunately many Linux distros do not offer it, and you'll probably have to build it from source... and that is a non-trivial task.
Typically a debugger is used to step through code line by line, starting at a chosen breakpoint, and keep watch of all variables/values.
Unit testing is a technique to test smaller pieces of code.
A stepping debugger, as found in most IDEs will help you with this.
Here (for example) is a description of how to set the Execution point in In Visual Studio, which sounds like what you want to do.
For certain situations, the "Immediate Window" may be of use to you. It allows you to type in expressions to evaluate immediately.
Rather than just running individual lines independently, or relying on print statements to tell you the state of whatever variables you have decided to print, you can use the debugger to run to the point of interest (where you will have set a breakpoint), then you can examine the state of any in-scope variables, or even alter the normal flow of the program.
There are some solutions that try to do this - the ones I know are Ch and TextTransformer.
However, I doubt that this works very well. C++ is not at all designed to run as an interpreted language.
One of the problems is that C++ is very, very hard to parse. And this makes it very hard to provide certain types of tools that are usual for other languages. For example, I don't think there is any C++ refactoring tool that really works well.
C++ is a compiled language not like python. But there are few c/c++ interpreters out there but not sure about their features. Check these out: Ch interpreter and CINT
If you really want to learn c++ please do not use the c/c++ interpreters.
If you insist on using a interactive interpreter there is since a long time CINT which is the default interpreter used in the ROOT project. It got better over the years, but still has only limited capabilities when dealing with templates. Also, there is a move to replace it with a JIT compiling interpreter based on clang inside the ROOT project.
If I were you I would learn how to run compiler and an interactive debugger like suggested in some comments already.