This point will not work. How to fix it. I understand that the CStrings leave the stack after the call to the function. are the any types of strings i C++ std:strings etc. Thats behave as C# strings. How I get it to work?
void Dialog1::GetOrderingKey(LPWSTR& lpOrderingKey)
{
CString OrderingKey;
m_Result.GetWindowText(OrderingKey);
lpOrderingKey = OrderingKey.GetBuffer(0);
}
LPWSTR lpOrderingKey;
GetOrderingKey(lpOrderingKey);
int returnValue = lpfnDllOrderingCodeDataW(lpSerialNumber, lpOrderingKey, data, _countof(data));
Just return a CString from GetOrderingKey():
CString Dialog1::GetOrderingKey()
{
CString OrderingKey;
m_Result.GetWindowText(OrderingKey);
return OrderingKey;
}
CString ordering_key = GetOrderingKey();
int returnValue = lpfnDllOrderingCodeDataW(lpSerialNumber, (LPCWSTR) ordering_key, data, _countof(data));
One straight forward and simplest way would be to declare it static.
void Dialog1::GetOrderingKey(LPWSTR& lpOrderingKey)
{
static CString OrderingKey;
Related
I currently have a function defined in a header that looks like this
void foo::GetValue(std::string& str);
This function basically assigns a value to str. I need to come up with an alternative to str (basically, nothing that employs the standard library).
The implementation of the above function is like this in the .cpp file:
void foo::GetValue(std::string& str)
{
std::string s = bar.someMethod();
str = s;
}
I want to know what is the best/easiest option for replacing the header?
One approach I had was to replace std::string in the header file with char* so I would have this in the header:
void foo::GetValue(char* str);
And in the implementation I would have this:
void foo::GetValue(char* str)
{
std::string resp = bar.someMethod();
char* c = new char[resp.size() + 1];
std::copy(resp.begin(), resp.end(), c);
c[resp.size()] = '\0';
}
The problem with the above approach is that a lot of files are calling this function and they will need to modify their code. Also, they will need to free the above memory. Two concerns I have with this is that other callers to this function will need to do the following two things
Replace std::string being passed to the function with char*.
Free the char* when done using it.
These two items seem very costly to me to trust other callers to do.
Any suggestions on what I can do to solve this problem? Perhaps change the signature to something else? I would prefer if the caller still passes a string, however string.c_str() is a constant char pointer.
For a given C++ function like this:
std::string foo::GetValue(std::string& str)
{
return bar.someMethod(str);
}
Then your equivalent C code looks like this:
void foo_GetValue(char* str, char* res, size_t size)
{
std::string str_arg = str;
std::string result = bar.someMethod(str_arg);
strncpy(res, result.c_str(), size - 1);
res[size-1] = 0; // Ensure is NUL terminated
}
When calling from C:
void example() {
const BUFFER_LEN = 1024;
char buffer[BUFFER_LEN];
foo_GetValue("example", buffer, BUFFER_LEN);
}
First, I am new to C++ (nearly a week into it), so forgive me if this is obvious. Also, I have hunted through many posts with similar issues. Either my understanding is just not developed enough, or none had relevant info to help me understand this issue.
In Metatrader 4, I am trying to figure out how to pass a structure variable to a dll, and modify variables stored in said structure. So far, I have had great success, even when dealing with structure arrays. Then I encountered an issue.
I have narrowed the problem down to the use of strings. If you will, please have a look at the following code, which I have used to focus on solving this problem, and help me understand why I keep getting this 'Access violation write to 0x00000000' error whenever I try and run the script in mt4.
The mql4 code:
struct Naming
{
string word;
} name;
#import "SampleDLLtest.dll"
bool NameTest(Naming &name);
#import
int init() { return(0); }
int start()
{
Print("original name: ", name.word);
if( NameTest( name ) )
{
Print("new name: ", name.word);
}
//---
return(0);
}
This is the relevant dll code:
#define WIN32_LEAN_AND_MEAN
#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
//---
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
//---
return(TRUE);
}
struct Naming
{
std::string n_name;
};
bool __stdcall NameTest(Naming *name)
{
name->n_name = "Captain Success";
return true;
}
From the documentation of mql4: http://docs.mql4.com/basis/preprosessor/import
The following can't be used for parameters in imported functions:
pointers (*);
links to objects that contain dynamic arrays and/or pointers.
Classes, string arrays or complex objects that contain strings and/or
dynamic arrays of any types cannot be passed as a parameter to
functions imported from DLL.
The imported function takes a pointer and that is apparently not supported by mql4.
You should probably use a fixed size array of characters to pass data to and from the dll:
like:
struct Naming {
char m_name[255];
}
The function would need to accept a reference to this struct (but this is probably not supported either) or accept the struct directly and return the struct.
Naming NameTest(Naming name) {
strncpy(name.m_name, "New Content", sizeof(name.m_name) -1);
if (sizeof(name.m_name) > 0) {
name.m_name[sizeof(name)-1] = 0;
}
return name;
}
Calling it would then look like this:
name = NameTest(name);
I know this is a bit odd, but I am answering my own question because I figured out what was going on....mostly at least.
So, here is the deal. Technically speaking, you can pass a structure that contains a string. What you cannot do is edit the string. There is no automatic conversion of a string to a char[] in the structure. So, when the dll attempts to edit the string, it throws up the access violation because a string is not really a string in C++, but is a char array disguised as a string.
That said, I did resolve how to pass a structure containing a string, and modify the value in the dll. Here is how I did it.
---Starting with the mql4 code---
First, I declared the struct with a char[] instead of a string.
struct Naming
{
char word[65];
} name;
Then I initialized the char[] with null value, checked it, passed the struct, and checked to see if the value was set correctly.
ArrayInitialize(name.word, '\0');
Print("original name: ", CharArrayToString(name.word));
if( NameTest( name ) )
{
Print("new name: ", CharArrayToString(name.word));
}
---now to the C++ code---
I declared the same struct.
struct Naming
{
char n_name[65];
};
Then the function. I first had to capture the string literal in a temporary char[]. The I cycled a for loop to distribute the elements to the char[] in the struct. The problem is, the char[] from the struct is not a const, and the char temp[] is. I got around this by capturing each char to a char variable, and then storing that variable value in the struct char[].
bool __stdcall NameTest(Naming *name)
{
char temp[] = "Captain Success";
for (int i = 0; temp[i] != '\0'; i++)
{
char t = temp[i];
name->n_name[i] = t;
}
return true;
}
This code works beautifully.
I have a DLL written in C++ that wraps FindFirstFile/FindNextFile/FindClose to provide a file-search function:
std::vector<std::wstring> ELFindFilesInFolder(std::wstring folder, std::wstring fileMask = TEXT(""), bool fullPath = false);
This function returns a std::vector containing a list of filenames within the given folder matching the given filemask. So far so good; the function works as expected.
I need to write a C wrapper around this library, though, because I can't pass a vector across DLL boundaries. This is leading to no end of headaches.
I initially thought I would just set up a function that would receive a two-dimensional wchar_t array, modify it to contain the filename list, and return it:
bool ELFindFilesInFolder(const wchar_t* folderPath, const wchar_t* fileMask, const bool fullPath, wchar_t* filesBuffer[], size_t* filesBufferSize);
This proved to be a bad idea, however, as at least the second dimension's size has to be known at compile-time. I suppose I could just force the caller to make the second dimension MAX_PATH (so the function would receive a variable-length list of filename buffers, each MAX_PATH long), but this seems messy to me.
I considered a wrapper in the style of the Windows APIs:
bool ELFindNextFileInFolder(const wchar_t* folderPath, const wchar_t* fileMask, const bool fullPath, wchar_t* fileBuffer, size_t* fileBufferSize, HANDLE* searchToken);
This would perform the search, return the first filename found, and save the search handle provided by FindFirstFile. Future calls to ELFindNextFileInFolder would provide this search handle, making it easy to pick up where the last call left off: FindNextFile would just get the saved search handle. However, such handles are required to be closed via FindClose, and C doesn't seem to have the C++ concept of a smart pointer so I can't guarantee the searchToken will ever be closed. I can close some of the HANDLEs myself when FindNextFile indicates there are no more results, but if the caller abandons the search before that point there'll be a floating HANDLE left open. I'd very much like my library to be well-behaved and not leak HANDLEs everywhere, so this is out. I'd also prefer not to provide an ELCloseSearchHandle function, since I'm not sure I can trust callers to use it properly.
Is there a good, preferably single-function way to wrap these Windows APIs, or am I simply going to have to pick one from a list of imperfect solutions?
What about something like this?
In the DLL module:
#include <windows.h>
#include <vector>
#include <unordered_map>
unsigned int global_file_count; //just a counter..
std::unordered_map<unsigned int, std::vector<std::wstring>> global_file_holder; //holds vectors of strings for us.
/** Example file finder C++ code (not exported) **/
std::vector<std::wstring> Find_Files(std::wstring FileName)
{
std::vector<std::wstring> Result;
WIN32_FIND_DATAW hFound = {0};
HANDLE hFile = FindFirstFileW(FileName.c_str(), &hFound);
if (hFile != INVALID_HANDLE_VALUE)
{
do
{
Result.emplace_back(hFound.cFileName);
} while(FindNextFileW(hFile, &hFound));
}
FindClose(hFile);
return Result;
}
/** C Export **/
extern "C" __declspec(dllexport) unsigned int GetFindFiles(const wchar_t* FileName)
{
global_file_holder.insert(std::make_pair(++global_file_count, Find_Files(FileName)));
return global_file_count;
}
/** C Export **/
extern "C" __declspec(dllexport) int RemoveFindFiles(unsigned int handle)
{
auto it = global_file_holder.find(handle);
if (it != global_file_holder.end())
{
global_file_holder.erase(it);
return 1;
}
return 0;
}
/** C Export **/
extern "C" __declspec(dllexport) const wchar_t* File_Get(unsigned int handle, unsigned int index, unsigned int* len)
{
auto& ref = global_file_holder.find(handle)->second;
if (ref.size() > index)
{
*len = ref[index].size();
return ref[index].c_str();
}
*len = 0;
return nullptr;
}
/** C Export (really crappy lol.. maybe clear and reset is better) **/
extern "C" __declspec(dllexport) void File_ResetReferenceCount()
{
global_file_count = 0;
//global_file_holder.clear();
}
extern "C" __declspec(dllexport) bool __stdcall DllMain(HINSTANCE hinstDLL, DWORD fdwReason, void* lpvReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(hinstDLL);
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
return true;
}
Then in the C code you can use it like:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
HMODULE module = LoadLibrary("CModule.dll");
if (module)
{
unsigned int (__cdecl *GetFindFiles)(const wchar_t* FileName) = (void*)GetProcAddress(module, "GetFindFiles");
int (__cdecl *RemoveFindFiles)(unsigned int handle) = (void*)GetProcAddress(module, "RemoveFindFiles");
const wchar_t* (__cdecl *File_Get)(unsigned int handle, unsigned int index, unsigned int* len) = (void*)GetProcAddress(module, "File_Get");
void (__cdecl *File_ResetReferenceCount)() = (void*)GetProcAddress(module, "File_ResetReferenceCount");
unsigned int index = 0, len = 0;
const wchar_t* file_name = NULL;
unsigned int handle = GetFindFiles(L"C:/Modules/*.dll"); //not an actual handle!
while((file_name = File_Get(handle, index++, &len)) != NULL)
{
if (len)
{
wprintf(L"%s\n", file_name);
}
}
RemoveFindFiles(handle); //Optional..
File_ResetReferenceCount(); //Optional..
/** The above two functions marked optional only need to be called
if you used FindFiles a LOT! Why? Because you'd be having a ton
of vectors not in use. Not calling it has no "leaks" or "bad side-effects".
Over time it may. (example is having 500+ (large) vectors of large strings) **/
FreeLibrary(module);
}
return 0;
}
It seems a bit dirty to be honest but I really don't know any "amazing" ways of doing it. This is just the way I do it.. Most of the work is done on the C++ side and you don't really have to worry about leaks.. Even exporting a function to clear the map would be nice too..
It would be better if the C exports were added to a template class and then export each of those.. That would make it re-useable for most C++ containers.. I think..
Change wchar_t* filesBuffer[] to wchar_t** *filesBuffer, then the caller can pass in a pointer to a wchar_t** variable to receive the array and does not need to know anything about any bounds at compile time. As for the array itself, the DLL can allocate a one-dimensional array of wchar_t* pointers that point to null-terminated strings. That way, your size_t* filesBufferSize parameter is still relevant - it receives the number of strings in the array.
bool ELFindFilesInFolder(const wchar_t* folderPath, const wchar_t* fileMask, const bool fullPath, wchar_t** *filesBuffer, size_t* filesBufferSize);
wchar_t **files;
size_t numFiles;
if (ELFindFilesInFolder(..., &files, &numFiles))
{
for(size_t i = 0; i < numFiles; ++i)
{
// use files[i] as needed ...
}
// pass files back to DLL to be freed ...
}
Another option is to do something similar to WM_DROPFILES does. Have ELFindFilesInFolder() return an opaque pointer to an internal list, and then expose a separate function that can retrieve a filename at a given index within that list.
bool ELFindFilesInFolder(const wchar_t* folderPath, const wchar_t* fileMask, const bool fullPath, void** filesBuffer, size_t* filesBufferSize);
bool ELGetFile(const wchar_t* fileName, size_t fileNameSize, void* filesBuffer, size_t fileIndex);
void *files;
size_t numFiles;
wchar_t fileName[MAX_PATH + 1];
if (ELFindFilesInFolder(..., &files, &numFiles))
{
for(size_t i = 0; i < numFiles; ++i)
{
ELGetFile(fileName, MAX_PATH, files, i);
// use fileName as needed ...
}
// pass files back to DLL to be freed ...
}
Any way you do it, the DLL has to manage the memory, so you have to pass some kind of state info to the caller and then have that passed back to the DLL for freeing. There is no many ways around that in C, unless the DLL keeps track of the state info internally (but then you have to worry about thread safety, reentrancy, etc) and frees it after the last file is retrieved. But that would require the caller to reach the last file, whereas the other approaches allow the caller to finish earlier if desired.
I hava a class likeļ¼
class SomeClass
{
void initFromBuffer(void* buffer,int length);
void initFromString(const std::string& str);
}
Using tolua++, got the binding like:
static int SomeClass_initFromBuffer00(lua_State* tolua_S)
{
SomeClass* self = (SomeClass*) tolua_tousertype(tolua_S,1,0);
void* buffer = ((void*) tolua_touserdata(tolua_S,2,0));
int length = ((int) tolua_tonumber(tolua_S,3,0));
self->initFromBuffer(buffer,length);
}
and:
static int SomeClass_initFromString00(lua_State* tolua_S)
{
SomeClass* self = (SomeClass*) tolua_tousertype(tolua_S,1,0);
const std::string str = ((const std::string) tolua_tocppstring(tolua_S,2,0));
self->initFromString(str);
tolua_pushcppstring(tolua_S,(const char*)str);
}
Now,i want to pass binary data from lua to c++,the binary has '\0' in it,so if i use initFromString to pass it, the binary data will be trimed. But if i use initFromBuffer to pass it, i got bad ptr at `void* buffer = ((void*) tolua_touserdata(tolua_S,2,0));, the pointer is null.
So, how could i pass binary string from lua to c++?
Maybe you should stop using Tolua's bad APIs and use plain Lua's actually good APIs. Both std::string and Lua strings are capable of storing embedded null characters. The only reason tolua_tocppstring causes truncation is because the function name is a lie. It doesn't convert it to a C++ string; it converts it to a C string, a const char*.
The correct answer is to use the proper API function:
std::string fromLuaStack(lua_State *lua, int stackIx)
{
size_t len;
const char *str = lua_tolstring(lua, stackIx, &len);
return std::string(str, len);
}
Similarly, you can use lua_pushlstring to push a std::string onto the stack.
It's unfortunate that Tolua doesn't have better documentation, as there may be a function to do this all directly. If there is, I couldn't find it.
Language: Visual C++, MFC
Environment: Visual Studio 2005
So I posted a similar question, but I've come to realize that I was asking the wrong question. I'm trying to use a loop to call a function on several different variables, but somewhere along the way, the program is crashing.
Simplified code is below, but I think it's actually easier to just explain it. I have a function that takes in a CString as a parameter. I have several variables I wish to feed to this function, so I put their names into an array, and I'm trying to pass them to the function that way.
// THE CODE BELOW IS WHAT I HAVE, BUT IT DOES NOT WORK //
Header File:
CString m_strTop;
CString m_strLeft;
CString m_strRight;
CString m_strBottom;
CString *var[4];
Source File:
Constructor()
CString *var[4] = {
&m_strTop
, &m_strLeft
, &m_strRight
, &m_strBottom
};
Source File:
theFunction()
void myClass::DoDataExchange(CDataExchange* pDX)
{
CSAPrefsSubDlg::DoDataExchange(pDX);
for(int i = 2001, j = 0; i <= 2004; i++, j++)
{
// THE LINE BELOW IS WHERE THINGS GO WONKY, SPECIFICALLY AT &var[j]
DDX_Text(pDX, i, *var[j]); // 'i' is the ID of the textbox
}
}
-- What DDX_Text expects --
void AFXAPI DDX_Text(
CDataExchange* pDX,
int nIDC,
CString& value
);
So like I said, I just need to feed the function the actual name of the variable. At least I think. What it's actually doing is establishing a connection between a text box in a dialog and the variable where the text box's input will be stored. I'm dereferencing correctly and everything, but I don't think this is the right approach.
Thank you for any help. And to people who answered my previous question, my apologies for misrepresenting the issue.
var is an array of pointers to CString.
var[j] is a pointer to CString.
&var[j] is a pointer to pointer to CString.
Now you need to pass the CString object. So you need:
DDX_Text(pDX, i, *var[j]); // dereference a pointer to CString.
Consider using std::vector instead of the C-array. It would be:
std::vector<CString> var(4);
...
DDX_Text(pDX, i, var[j]); // pass a CString object
I've noted that you're declaring variable var once again in the constructor:
CString *var[4] = { // this declares new temporary variable,
// it doesn't initialize one from the header file
&m_strTop
, &m_strLeft
, &m_strRight
, &m_strBottom
};
Shouldn't it be? :
var[0] = &m_strTop;
var[1] = &m_strLeft;
var[2] = &m_strRight;
var[3] = &m_strBottom;
I suppose you need the following:
// header file
class myClass
{
std::vector<CString> var_;
...
};
// source file
myClass::myClass() : var_(4)
{
...
}
void myClass::theFunction(CDataExchange* pDX)
{
CSAPrefsSubDlg::DoDataExchange(pDX);
for(int i = 2001, j = 0; i <= 2004; i++, j++)
{
DDX_Text(pDX, i, var_[j]); // 'i' is the ID of the textbox
}
}
You're not passing the right thing into DDX_Text. It's third parameter is a reference to a CString. You're passing in the address of a pointer. So you should probably do something like
DDX_Test(pDX, i, *var[j]);