I have text file with the name By_a_waterfal.txt and the following content:
By a waterfal I'm calling you.
We can share it all beneath a ceiling of blue.
We'll spend a heavenly day
Here where the whispering waters play.
I create memory mapping of this file by calls of function:
HANDLE hFileMapping = CreateFileMapping(handleOfFile, NULL, PAGE_READ, 0, 0, NULL);
Where handleOfFile is the handle of By_a_waterfal.txt file.
Then I do the following call:
LPVOID lpFileMap = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
How can I get access to content of the memory mapped By_a_waterfal.txt file via the view created with MapViewOfFile call?
If you really have to use memory mapping instead if std::ifstream, then:
1) Check lpFileMap for NULL.
2) Get size of view as GetFileSize(handleOfFile) or VirtualQuery(lpFileMap).
3) If file has ANSI encoding (not Unicode) cast lpFileMap to char* and proceed (do not forget that there is no 0-terminator)
auto data = static_cast<const char*>(lpFileMap);
std::string strData(data, size);
std::cout << stdData;
lpFileMap is a pointer to the content. If you want the content as a const char* for instance, just cast it:
const char* content = static_cast<const char*>(lpFileMap);
Related
Hey I'm new to C++ and I am trying to find out if a specified registry index exists. I have to check multiple locations due to the possibility of the software being run on a 64bit machine and being under the WOW6432Node key instead of the usual position. When RegQueryValueExA (using visual c++ 6.0 on xp so I can't use a newer function) is run it should return a Boolean of true if the key exists, (I'll deal with getting the value of the key later). However on run it generates access violation 0xc00005. Any ideas whats gone wrong?
bool FindAndRemoveUninstall(string path){
bool result;
result = RegQueryValueExA(HKEY_LOCAL_MACHINE,
TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\ABC"), NULL, NULL, NULL, (unsigned long *)MAX_PATH);
if (result= ERROR_SUCCESS){
cout <<" is a 32 bit program\n";
//path= Value in key
}
result = RegQueryValueEx(HKEY_LOCAL_MACHINE,
TEXT("SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\ABC"), NULL, NULL, NULL, (unsigned long *)MAX_PATH);
if (result= ERROR_SUCCESS){
cout << " is 64 bit program\n";
//path= Value in key
}
return true;
}
You have multiple problems.
The last parameter to RegQueryValueExA is documented as
lpcbData [in, out, optional]
A pointer to a variable that specifies the size of the buffer pointed to by the lpData parameter,
But you are not passing a pointer to a variable. You are passing (unsigned long *)MAX_PATH, which is a garbage pointer. When the operating system tries to store the result into the pointer, it takes an access violation. You need to pass a pointer to a variable, like the documentation says.
The next problem is that you are calling the A function (explicit ANSI) but using the TEXT macro (adaptive character set). Make up your mind which model you are using (ANSI or adaptive) and choose one model or the other. Let's assume you explicit ANSI.
The next problem is that you didn't specify an output buffer, so you don't actually retrieve the path.
Another problem is that the RegQueryValueExA function does not return a bool; it returns an error code.
Yet another problem is that your if test contains an assignment, so it does not actually test anything.
Another problem is that you didn't specify a way for the function to return the path to the caller. Let's assume you want the result to be returned in the path parameter.
Yet another problem is that you have the 32-bit and 64-bit cases reversed.
Also, you are using '\n' instead of std::endl.
The eight problem is that your function returns true even if it didn't do anything.
And the ninth problem is that the function says FindAndRemove, and it finds, but doesn't remove.
bool FindUninstall(string& path){ // parameter passed by reference, fix function name
LONG result; // change variable type
char buffer[MAX_PATH]; // provide an output buffer
DWORD bufferSize = MAX_PATH; // and a variable to specify the buffer size / receive the data size
result = RegQueryValueExA(HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\ABC", NULL, NULL, (LPBYTE)buffer, &bufferSize); // remove TEXT macro, pass the buffer and buffer size
if (result== ERROR_SUCCESS){ // fix comparison
cout <<" is a 64 bit program" << std::endl; // fix message
path = buffer;
return true; // stop once we have an answer
}
buffersize = MAX_PATH; // reset for next query
result = RegQueryValueEx(HKEY_LOCAL_MACHINE,
"SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\ABC", NULL, NULL, (LPBYTE)buffer, &bufferSize); // remove TEXT macro, pass the buffer and buffer size
if (result== ERROR_SUCCESS){ // fix comparison
cout << " is 32 bit program" << std::endl; // fix message
path = buffer;
return true; // stop once we have an answer
}
return false; // nothing found
}
Since you are new to C++, I would recommend that you get some experience with C++ doing simpler projects before diving into more complicated things like this.
I am implementing a virtual filesystem using the fuse, and need some understanding regarding the offset parameter in readdir.
Earlier we were ignoring the offset and passing 0 in the filler function, in which case the kernel should take care.
Our filesystem database, is storing: directory name, filelength, inode number and parent inode number.
How do i calculate get the offset?
Then is the offset of each components, equal to their size sorted in incremental form of their inode number? What happens is there is a directory inside a directory, is the offset in that case equal to the sum of the files inside?
Example: in case the dir listing is - a.txt b.txt c.txt
And inode number of a.txt=3, b.txt=5, c.txt=7
Offset of a.txt= directory offset
Offset of b.txt=dir offset + size of a.txt
Offset of c.txt=dir offset + size of b.txt
Is the above assumption correct?
P.S: Here are the callbacks of fuse
The selected answer is not correct
Despite the lack of upvotes on this answer, this is the correct answer. Cracking into the format of the void buffer should be discouraged, and that's the intent behind declaring such things void in C code - you shouldn't write code that assumes knowledge of the format of the data behind void pointers, use whatever API is provided properly instead.
The code below is very simple and straightforward, as it should be. No knowledge of the format of the Fuse buffer is required.
Fictitious API
This is a contrived example of what some device's API could look
like. This is not part of Fuse.
// get_some_file_names() -
// returns a struct with buffers holding the names of files.
// PARAMETERS
// * path - A path of some sort that the fictitious device groks.
// * offset - Where in the list of file names to start.
// RETURNS
// * A name_list, it has some char buffers holding the file names
// and a couple other auxiliary vars.
//
name_list *get_some_file_names(char *path, size_t offset);
Listing the files in parts
Here's a Fuse callback that can be registered with the Fuse system to
list the filenames provided by get_some_file_names(). It's arbitrarily named readdir_callback() so its purpose is obvious.
int readdir_callback( char *path,
void *buf, // This is meant to be "opaque".
fuse_fill_dir_t *filler, // filler takes care of buf.
off_t off, // Last value given to filler.
struct fuse_file_info *fi )
{
// Call the fictitious API to get a list of file names.
name_list *list = get_some_file_names(path, off);
for (int i = 0; i < list->length; i++)
{
// Feed the file names to filler() one at a time.
if (filler(buf, list->names[i], NULL, off + i + 1))
{
break; // filler() returned 1, requesting a break.
}
incr_num_files_listed(list);
}
if (all_files_listed(list))
{
return 1; // Tell Fuse we're done.
}
return 0;
}
The off (offset) value is not used by the filler function to fill its opaque buffer, buf. The off value is, however, meaningful to the callback as an offset base as it provides file names to filler(). Whatever value was last passed to filler() is what gets passed back to readdir_callback() on its next invocation. filler()
itself only cares whether the off value is 0 or not-0.
Indicating "I'm done listing!" to Fuse
To signal to the Fuse system that your readdir_callback() is done listing file names in parts (when the last of the list of names has been given to filler()), simply return 1 from it.
How off Is Used
The off, offset, parameter should be non-0 to perform the partial listings. That's its only requirement as far as filler() is concerned. If off is 0, that indicates to Fuse that you're going to do a full listing in one shot (see below).
Although filler() doesn't care what the off value is beyond it being non-0, the value can still be meaningfully used. The code above is using the index of the next item in its own file list as its value. Fuse will keep passing the last off value it received back to the read dir callback on each invocation until the listing is complete (when readdir_callback() returns 1).
Listing the files all at once
int readdir_callback( char *path,
void *buf,
fuse_fill_dir_t *filler,
off_t off,
struct fuse_file_info *fi )
{
name_list *list = get_all_file_names(path);
for (int i = 0; i < list->length; i++)
{
filler(buf, list->names[i], NULL, 0);
}
return 0;
}
Listing all the files in one shot, as above, is simpler - but not by much. Note that off is 0 for the full listing. One may wonder, 'why even bother with the first approach of reading the folder contents in parts?'
The in-parts strategy is useful where a set number of buffers for file names is allocated, and the number of files within folders may exceed this number. For instance, the implementation of name_list above may only have 8 allocated buffers (char names[8][256]). Also, buf may fill up and filler() start returning 1 if too many names are given at once. The first approach avoids this.
The offset passed to the filler function is the offset of the next item in the directory. You can have the entries in the directory in any order you want. If you don't want to return an entire directory at once, you need to use the offset to determine what gets asked for and stored. The order of items in the directory is up to you, and doesn't matter what order the names or inodes or anything else is.
Specifically, in the readdir call, you are passed an offset. You want to start calling the filler function with entries that will be at this callback or later. In the simplest case, the length of each entry is 24 bytes + strlen(name of entry), rounded up to the nearest multiple of 8 bytes. However, see the fuse source code at http://sourceforge.net/projects/fuse/ for when this might not be the case.
I have a simple example, where I have a loop (pseudo c-code) in my readdir function:
int my_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi)
{
(a bunch of prep work has been omitted)
struct stat st;
int off, nextoff=0, lenentry, i;
char namebuf[(long enough for any one name)];
for (i=0; i<NumDirectoryEntries; i++)
{
(fill st with the stat information, including inode, etc.)
(fill namebuf with the name of the directory entry)
lenentry = ((24+strlen(namebuf)+7)&~7);
off = nextoff; /* offset of this entry */
nextoff += lenentry;
/* Skip this entry if we weren't asked for it */
if (off<offset)
continue;
/* Add this to our response until we are asked to stop */
if (filler(buf, namebuf, &st, nextoff))
break;
}
/* All done because we were asked to stop or because we finished */
return 0;
}
I tested this within my own code (I had never used the offset before), and it works fine.
How could you wrap the IO functions in Lua to prevent someone from leaving your top level directory.
You place them in "MyDoc" and they have full IO access to everything sub of MyDoc but couldn't for example .. back into the C drive or anywhere else.
open up liolib.c. head over to these 3 functions
static void opencheck (lua_State *L, const char *fname, const char *mode) {
LStream *p = newfile(L);
p->f = fopen(fname, mode);
if (p->f == NULL)
luaL_error(L, "cannot open file " LUA_QS " (%s)", fname, strerror(errno));
}
static int io_open (lua_State *L) {
const char *filename = luaL_checkstring(L, 1);
const char *mode = luaL_optstring(L, 2, "r");
LStream *p = newfile(L);
const char *md = mode; /* to traverse/check mode */
luaL_argcheck(L, lua_checkmode(md), 2, "invalid mode");
p->f = fopen(filename, mode);
return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
}
static int io_popen (lua_State *L) {
const char *filename = luaL_checkstring(L, 1);
const char *mode = luaL_optstring(L, 2, "r");
LStream *p = newprefile(L);
p->f = lua_popen(L, filename, mode);
p->closef = &io_pclose;
return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
}
these are the functions you want to edit.
the first one receives the file name as the parameter fname, the second and the third
pop it out of the lua stack as the local variable filename.
now all you need to do is
1) get your own process path
2) canonize the given file path
3) compare them so that they are the same up until the last slash on both
4) if they are not the same then in opencheck use luaL_error(L,"access denied to %s", fname);
in the other two return luaL_fileresult(L,0,filename);
Presumably you have sandboxed your user environment, so for instance they can't use the builtin "require" or "dofile" or "setatable"? Basically you have to limit the functions they can call to only what you want, and create your own versions of anything you want to control. There are several ways to do this and they each have their pros and cons and nothing is unbreakable, all you can do is up the bar of experience, effort and time required to break your "jail".
This means you have to work at the C API level, but I would not recommend modifying the source unless you are very familiar with it and can easily determine that your modifications aren't easiy breakable. By staying at the C API level, at least other Lua users can help validate the solidity of the sandbox.
You have to figure out a way to enable your code to call Lua builtin without allowing the user to call the builtin. I believe you can store tables in the lua registry, where only the C code can look. It's been a while. Or maybe if you don't put getmetable in user environment, that allows you to call the builtins via metatable but user can't get to them.
For example, from C
you load the builtins such as io module and save the functions you will wrap (such as open) in a (meta)table table;
delete the builtin table io from _G so user only has access to the version you created; you've saved the functions you will need for later
create a global table called io and set its metatable to what you created in step 1, so it defines only functions you want to give access to, such as a function called "open".
In that function you do whatever filtering you need, before calling the builtin you saved.
The details will make a big difference, and implementation will be different if you use Lua 5.1 vs 5.2, but there are several good articles on sandboxing in Lua on the web (sorry no time to find), take a look and come up with something, then maybe post on Lua user mailing list or SO for pros/cons. ;)
I am using vtkImageImport to convert from an opencv matrix to vtkImageData.
vtkImageData* convertImage(const cv::Mat& image)
{
int width = image.cols;
int height = image.rows;
vtkSmartPointer<vtkImageImport> importer = vtkSmartPointer<vtkImageImport>::New();
importer->SetDataScalarTypeToUnsignedChar();
importer->SetImportVoidPointer(image.data);
importer->SetWholeExtent(0,width-1,0, height-1, 0, 0);
importer->SetDataExtentToWholeExtent();
importer->Update();
return importer->GetOutput();
}
I have 2 questions on how pointers and memory are managed when doing this kind of import.
Does the importer create and allocate a new data pointer for the vtkImageData created, so that the vtk image is not affected when the opencv matrix is destroyed.
Will the returned vtkImageData* still be valid once the importer is destroyed, or should I return a smart pointer to keep the reference counting > 0? My reasoning is that if the importer uses smart pointers for the vtkImageData internally, then the image will be destroyed as the importer is destroyed. VTK examples always use the importer in the same scope as where the data is then used.
Thank you
The importer does a copy when you ask to do it.
void vtkImageImport::SetImportVoidPointer (void* ptr, int save); stores your void* pointer without copying the data, save arg is used in the destructor of ImgImport, if save is 1, your stored pointer will not be deleted.
void SetImportVoidPointer (void *ptr) calls previous methods with save=1, so in your code, data from CV::Mat, will not be destroyed. Be careful : both use the same pointer : Modify your CV::Mat; and the result from importer will be different.
void CopyImportVoidPointer (void *ptr, vtkIdType size); make a copy of your data, in this case, internally, ImgImport will copy the data, store the new pointer, and delete it in the destructor. You can delete your CV::Mat, it may not affect the Importer.
For the second question, i'm not sure of the internally behavior for retrieve the output but storing the output from a vtkAlgorithm in a vtkSmartPointer allows you to delete the algorithm without corrupt the data.
vtkSmartPointer<vtkImageData> convertImage(const cv::Mat& image)
{
int width = image.cols;
int height = image.rows;
vtkSmartPointer<vtkImageImport> importer = vtkSmartPointer<vtkImageImport>::New();
importer->SetDataScalarTypeToUnsignedChar();
importer->SetImportVoidPointer(image.data);
importer->SetWholeExtent(0,width-1,0, height-1, 0, 0);
importer->SetDataExtentToWholeExtent();
importer->Update();
vtkSmartPointer<vtkImageData> outp = importer->GetOutput();
importer->Delete (); // this line cause the destruction of the output, unless it's stored in a smartPointer.
return outp;
}
Importer->Delete() is just for example. I tried with a basic exemple, and I as able to use the output from a vtkAlgorithm, without storing the output in a smartPointer.
But reading the Vtk official tutorials (section "Getting an Object with a Smart Pointer"), if you don't store the output in a smartpointer, the importer may be deleted at the end of the scope, the data too.
That's why i'm not sure : I can still use the "direct" pointer returned by the convertImage methods. You must use the smartpointers as describes in the VTK tutos. It's the best way to be sure your data is valid .
Hope it help.
GetDIBits: trying to modify the bitmap, but not sure how to go about it? I tried lpvBits but it crashes out in the comparison in the "pig" area. How should I do this? thx
LPVOID lpvBits=NULL; // pointer to bitmap bits array
BITMAPINFO bi;
ZeroMemory(&bi.bmiHeader, sizeof(BITMAPINFOHEADER));
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
if (!GetDIBits(dc, m_bmp, 0, 400, lpvBits, &bi, DIB_RGB_COLORS))
AfxMessageBox("1");
char *pig = (char*)lpvBits;
for (int m=0;m<100;m++)
{
if (pig[m] > 100)
{
pig[m] = 250;
}
}
SetDIBits( dc, m_bmp, 0, 400, (void *)pig, &bi, DIB_RGB_COLORS );
http://msdn.microsoft.com/en-us/library/dd144879(v=vs.85).aspx
lpvBits [out]
A pointer to a buffer to receive the bitmap data. If this parameter is NULL, the function passes the dimensions and format of the bitmap to the BITMAPINFO structure pointed to by the lpbi parameter.
example found here:
http://msdn.microsoft.com/en-us/library/dd183402(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ms969901.aspx
http://www.codeproject.com/KB/graphics/drawing2bitmap.aspx
http://www.cplusplus.com/forum/general/28469/
Read the documentation for GetDIBits carefully - the lpvBits pointer is not returned to you - you need to allocate enough memory for the bitmap data you want to fetch, and pass it to GetDIBits to fill it in with image data.