Bind void * pointer to C++/Cli pointer of elementary type - pointers

I do some thin wrapper of some scientific library (http://root.cern.ch) from unmanaged to managed world using C++ cli.
Reading of the special file format (which is the main goal) is implemented through:
1) Once a lifetime call of SetBranchAddress(const char name, void* outputVariable) to let it know an address of your variable
2) Than you N time call GetEntry(ulong numberOfRow) wthich fills this void* outputVariable with the appropriate value;
I put this example of usage :
double myValue; //this field will be filled
//We bind myValue to the 'column' called "x" stored in the file"
TTree->SetBranchAddress("x", &myValue);
// read first "entry" (or "row") of the file
TTree->GetEntry(0);
// from that moment myValue is filled with value of column "x" of the first row
cout<<"First entry x = "<<myValue<<endl;
TTree->GetEntry(100); //So myValue is filled with "x" of 101 row
...
So in C++/CLI code the problem is with binding managed elementary types to this void * pointer;
I have tried 3 approaches:
namespace CppLogicLibrary {
public ref class SharpToRoot
{
double mEventX;
double *mEventY;
IntPtr memEventZ;
///Constructor
SharpToRoot()
{
mEventy = new double();
memEventZ= Marshal::AllocHGlobal(sizeof(double));
}
void SetBranchAddresses()
{
pin_ptr<double> pinnedEventX = &mEventX;
mTree->SetBranchAddress("ev_x", pinnedEventX);
mTree->SetBranchAddress("ev_y", mEventY);
mTree->SetBranchAddress("ev_z", memEventZ.ToPointer());
...
//now I read some entry to test... just in place
mTree->GetEntry(100);
mTree->GetEntry(101);
double x = mEventX;
double y = *mEventY
double z = (double)Marshal::PtrToStructure(memEventZ, Double::typeid);
}
...
All of 3 variants are compiled with no errors, goes with no exceptions... BUT fills its (void *) values with some rubbish value like 5,12331E-305. In unmanaged code all works fine.
What could be the error with such void* to C++/CLI elementary types binding?

The problem was that internally data was presented by floats inside of this library. So, when it was mapped and processed as doubles on the C# side, it gave 5,12331E-305.
Each of this 3 variats worked. And, from my point of view, using of
pin_ptr pinnedEventX = &mEventX;
was improper in this case, because it doesn't persist between functions execution;
What I'm not sure, why this "float" situation was handled in native C++. As I wrote before, there wasn't any problem.

Related

Pushing values to a Vector of pointers has garbage values

I am a C++ noob and I have written a method to get text file names including full-paths from a given directory. It gives a garbage value on the vector<wchar_t*> names. I used VS2010 debugger and analysed values. It looks like pointers are going out of scope. On the official C++ reference it says that push_back() copies values and seems like as I am pushing a pointer and it just copies pointers value.
static std::vector<wchar_t*> getFileNames(wchar_t* folder) // ex: c:\\textfiles\\My
{
using namespace std;
vector<wchar_t*> names;
wchar_t search_path[200];
swprintf(search_path, L"%s\\*.txt", folder); // ex: c:\\textfiles\\My\\*.txt
WIN32_FIND_DATA fd;
HANDLE hFind = FindFirstFile((wchar_t*)search_path, &fd);
if(hFind != INVALID_HANDLE_VALUE)
{
do
{
if(! (fd.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) )
{
std::wstring fullPath(folder);
fullPath += L"\\";
fullPath += std::wstring(fd.cFileName); // cFilename has something like Info.txt
names.push_back((wchar_t*)fullPath.c_str());
}
}while(FindNextFile(hFind, &fd)); //goes out of scope and values become garbage
FindClose(hFind);
}
return names; //vector with garbage values
}
Is it possible to get wchar_t* pushed in to the vector someway, a better work around rather than dynamically allocating memory or using heap variables?
Can I get compiler warning for mistakes like this on VS2010 or any VS version(Now I only get casting warning and errors)?
swprintf might overflow the buffer.
(wchar_t*)search_path is a superfluous cast.
Never break out the big guns if you don't need them.
if(! (fd.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) ) means you only ignore directories without interesting attributes.
fullPath += std::wstring(fd.cFileName); another superfluous cast.
names.push_back((wchar_t*)fullPath.c_str()); pushes a pointer to the internal buffer of fullpath into names, even though it will be destroyed at the end of the block.
What you should do is change the signature to
static std::vector<std::wstring> getFileNames(std::wstring folder)
Or at least
static std::vector<std::unique_ptr<wchar_t>> getFileNames(wchar_t* folder)
to take advantage of RAII and reduce the chance for errors.
In any case, you should rewrite the function, and should take advantage of the standard-library internally.
As an example, with the proper prototype:
static std::vector<std::wstring> getFileNames(std::wstring folder) {
std::vector<std::wstring> names;
WIN32_FIND_DATA fd;
HANDLE hFind = FindFirstFile((folder+L"\\*.txt").c_str(), &fd);
if(hFind == INVALID_HANDLE_VALUE)
return names;
auto lam = [](HANDLE* p){FindClose(*p);}
std::unique_ptr<HANDLE, decltype(lam)> guard(&hFind, lam);
folder += L"\\";
do {
if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )
names.push_back(folder+fd.cFileName);
} while(FindNextFile(hFind, &fd));
return names;
}
Ideally, you should store class objects in your vector, instead of character pointers (or wchar_t pointers). You can do it, but it requires some extra work. That's the part that you're missing.
The issue you're seeing is exactly what you describe: the character arrays that are owned by the wstring objects are being destroyed when the wstring goes out of scope. By using wstring::c_str(), you are not creating an independent copy of the character array, you're just looking at the one that it already has created for its own use.
So you need a way to keep a character array around longer. Either you could use the wstring, or you need to copy the character array into one of your own.
The minimal change would be something like this:
std::wstring fullPath(folder);
fullPath += L"\\";
fullPath += std::wstring(fd.cFileName); // cFilename has something like Info.txt
wchar_t *wsz = new wchar_t[fullPath.size() + 1];
wcsncpy(wsz, fullPath.c_str(), fullPath.size());
names.push_back(wsz);
That's enough to get your strings into the vector, but because you're using character pointers, it's also your responsibility to clean them up. So when you are done using the vector, you will need to iterate through and delete each one of them before you let the vector be destroyed.
As I mention in a comment below, it's much simpler to use a std::vector. There are libraries that can help you with the memory management parts, if you must use wchar_t*. You caould take a look at the Boost Smart Pointer library, for example.
The variable fullPath is a local variable.
It goes out of scope.
That is the reason the pointers are becoming junk.
Allocate a dynamic memory as
vector<wstring*> names;// instead of vector<wchar_t*> names;
std::wstring *fullPath = new wstring(folder);
Never store references of objects into a list if you are not aware of their scope.

QMap Memory Error

I am doing one project in which I define a data types like below
typedef QVector<double> QFilterDataMap1D;
typedef QMap<double, QFilterDataMap1D> QFilterDataMap2D;
Then there is one class with the name of mono_data in which i have define this variable
QFilterMap2D valid_filters;
mono_data Scan_data // Class
Now i am reading one variable from a .mat file and trying to save it in to above "valid_filters" QMap.
Qt Code: Switch view
for(int i=0;i<1;i++)
{
for(int j=0;j<1;j++)
{
Scan_Data.valid_filters[i][j]=valid_filters[i][j];
printf("\nValid_filters=%f",Scan_Data.valid_filters[i][j]);
}
}
The transferring is done successfully but then it gives run-time error
Windows has triggered a breakpoint in SpectralDataCollector.exe.
This may be due to a corruption of the heap, and indicates a bug in
SpectralDataCollector.exe or any of the DLLs it has loaded.
The output window may have more diagnostic information
Can anyone help in solving this problem. It will be of great help to me.
Thanks
Different issues here:
1. Using double as key type for a QMap
Using a QMap<double, Foo> is a very bad idea. the reason is that this is a container that let you access a Foo given a double. For instance:
map[0.45] = foo1;
map[15.74] = foo2;
This is problematic, because then, to retrieve the data contained in map[key], you have to test if key is either equal, smaller or greater than other keys in the maps. In your case, the key is a double, and testing if two doubles are equals is not a "safe" operation.
2. Using an int as key while you defined it was double
Here:
Scan_Data.valid_filters[i][j]=valid_filters[i][j];
i is an integer, and you said it should be a double.
3. Your loop only test for (i,j) = (0,0)
Are you aware that
for(int i=0;i<1;i++)
{
for(int j=0;j<1;j++)
{
Scan_Data.valid_filters[i][j]=valid_filters[i][j];
printf("\nValid_filters=%f",Scan_Data.valid_filters[i][j]);
}
}
is equivalent to:
Scan_Data.valid_filters[0][0]=valid_filters[0][0];
printf("\nValid_filters=%f",Scan_Data.valid_filters[0][0]);
?
4. Accessing a vector with operator[] is not safe
When you do:
Scan_Data.valid_filters[i][j]
You in fact do:
QFilterDataMap1D & v = Scan_Data.valid_filters[i]; // call QMap::operator[](double)
double d = v[j]; // call QVector::operator[](int)
The first one is safe, and create the entry if it doesn't exist. The second one is not safe, the jth element in you vector must already exist otherwise it would crash.
Solution
It seems you in fact want a 2D array of double (i.e., a matrix). To do this, use:
typedef QVector<double> QFilterDataMap1D;
typedef QVector<QFilterDataMap1D> QFilterDataMap2D;
Then, when you want to transfer one in another, simply use:
Scan_Data.valid_filters = valid_filters;
Or if you want to do it yourself:
Scan_Data.valid_filters.clear();
for(int i=0;i<n;i++)
{
Scan_Data.valid_filters << QFilterDataMap1D();
for(int j=0;j<m;j++)
{
Scan_Data.valid_filters[i] << valid_filters[i][j];
printf("\nValid_filters=%f",Scan_Data.valid_filters[i][j]);
}
}
If you want a 3D matrix, you would use:
typedef QVector<QFilterDataMap2D> QFilterDataMap3D;

C++/CLI How to translate this code ?

I dont know a lot about C++, but I have to make work some C++ code with .NET. I try with DLLImport but I failed. So I try with C++/CLI to make kind of a wrapper.
But I'm not sure to understand everything...
This is the basic C++ H file with the function I want to export (MyFunction)
extern "C"
{
__declspec(dllexport) IplImage* MyFunction(IplImage *src, std::string* name, OneEnumerationType myEnum, bool myBool, float myFloat);
}
This is the Wrapper h code.
#include "MyFunction.h"; // the file containing the h code
#include <string>
namespace MyWrapper{
public ref class MyWrapperClass {
public:
MyWrapper(){};
IplImage^ GetMyFunction(IplImage *src, std::string^ name, OneEnumerationType myEnum, bool myBool, float myFloat);
}
This is the Wrapper cpp code.
#include "MyWrapperCode.h";
namespace MyWrapper{
IplImage^ MyWrapperClass::GetMyFunction(IplImage* src, std:string^ name, OneEnumerationType myEnum, bool myBool, float myFloat){
MyFunction(src, name, myEnum, myBool, myFloat);
}
}
These are my questions :
1) When I'm compiling, the error is "'^ : cannot use this indirection on type IplImage' and same message for type "std::string".
I have followed this logical :
ClasseNative clNat2 = *clNat; --> ClasseManagee clMan2 = *clMan;
ClasseNative &clNat3 = clNat2; --> ClasseManagee %clMan3 = clMan2;
ClasseNative *clNat4 = &clNat2; --> ClasseManagee ^clMan4 = %clMan2;
I have seen, that It was better to use System::String. I try this way but the initial function is using std::string... BTW, why is it better to change ?
2) How do I get the MyFunction IplImage result ? Thru a private member and a get I suppose but I dont know how to initialize it...
3) Tricky question. Is it possible for me to put the CLI obtains IplImage structure (from the OpenCV library) (the result of my function) inside a IplImage .NET structure, when I ll called my wrapper ? Dont know if the question is understandable...
Thanks a lot for your help.
Turning around for 3 days on this problem...
Your wrapper class needs to create a new std::string based on the content of a System::String^ parameter then pass to your native function. Otherwise you need to rewrite the function to take something else as the string input, for example a LPWSTR or LPCSTR.
You can write a ref class to have properties for all data that an IplImage would have, then pass that to your wrapper class. Your wrapper class then create an IplImage object based on the data of the ref class and pass to the native function. Reverse the data copying direction for the return value.
1) just by adding ^ you cannot change a native object to become managed, you have to create wrappers or transfer the data for example:
std::string nativeString = "my string";
String^ managedString = gcnew String(nativeString.c_str());
//now you can return it as
2) create a managed wrapper or use primitive datatype to transfer the data
3) note sure if this will help but look at Emgu.CV
try reading abit more about C++\CLI here are a few nice tutorials:
Quick C++/CLI - Learn C++/CLI in less than 10 minutes
C++/CLI for the C# programmer

Problems with a structure copy

I am having a compiler issue in Visual Studio 2005 using the standard C compiler when trying to do a structure copy from one location to another.
The types are defined in a file as follows:
definition.h
#define MAX 7
typedef struct{
char recordtext[18];
boolean recordvalid;
}recordtype;
typdef recordtype tabletype[MAX];
typedef struct{
tabletype table;
}global_s;
Let us pretend that a global_s "object" is instantiated and initialized somewhere and a pointer to this structure is created.
#include "definition.h"
global_s global;
global_s* pglobal = &global;
init(&pglobal);
Meanwhile, in another file (and this is where my problem is) i am trying to create a local tabletype object, and fill it with the global table member, using a get method to protect the global (lets pretend it is "static")
#include "definition.h"
extern global_s* pglobal;
tabletype t;
gettable(&t);
void gettabl (tabletype* pt)
{
*pt = pglobal->table;
}
When I go to compile, the line in the gettable function throws a compiler error "error C2106: '=': left operand must be l-value. It looks as though this should behave as a normal copy operation, and in fact if I perform a similar operation on a more basic structure I do not get the error. For example If I copy a structure only containing two integers.
Does anyone have a solid explanation as to why this operation seems to be incorrect?
(Disclaimer: I have developed this code as a scrubbed version of my actual code for example purposes so it may not be 100% correct syntactically, I will edit the question if anyone points out an issue or something needs to be clarified.)
It's the arrays in the struct; they cannot be assigned. You should define an operator=() for each of the structs, and use memcpy on the arrays, or copy them in a loop element by element.
(IF you want to get a reference to your global variable):
I am not sure, if this is correct (and the problem), but I think besides function prototypes, arrays and pointers (to arrays 1. element) are NOT exactly the same thing. And there is a difference between pointer to array and pointer to the 1. element of an array)
Maybe taking the adress of the array:
*pt = &(pglobal->table);
Anyway it might be better not to fetch the address of the whole array but the address of the first element, so that the resulting pointer can be used directly as record array (without dereferencing it)
recordtype* gettable (size_t* puLength)
{
*puLength = MAX;
return &(pglobal->table[0]);
}
(IF you want a copy of the table):
Arrays can't be copied inplace in C90, and of course you have to provide target memory. You would then define a function get table like this:
void gettable (recordtype * const targetArr)
{
size_t i = 0;
for (; i < MAX; i++) targetArr[i] = pglobal->table[i];
return;
}
an fully equivalent function prototype for gettable is:
void gettable(recordtype[] targetArr);
Arrays are provided by refernce as pointer to the first element, when it comes to function parameters. You could again ask for an pointer to the whole array, and dereference it inside gettable. But you always have to copy elementwise.
You can use memcopy to do the job as 1-liner. Modern compilers should generate equally efficent code AFAIK.

CLI/C++: void* to System::Object

This is a similar question to this SO post, which I have been unable to use to solve my problem. I have included some code here, which will hopefully help someone to bring home the message that the other posting was getting at.
I want to write a CLI/C++ method that can take a void pointer as a parameter and return the managed object (whose type I know) that it points to. I have a managed struct:
public ref struct ManagedStruct { double a; double b;};
The method I am trying to write, which takes a void pointer to the managed struct as a parameter and returns the struct.
ManagedStruct^ VoidPointerToObject(void* data)
{
Object^ result = Marshal::PtrToStructure(IntPtr(data), Object::typeid);
return (ManagedStruct^)result;
}
The method is called here:
int main(array<System::String ^> ^args)
{
// The instance of the managed type is created:
ManagedStruct^ myData = gcnew ManagedStruct();
myData->a = 1; myData->b = 2;
// Suppose there was a void pointer that pointed to this managed struct
void* voidPtr = &myData;
//A method to return the original struct from the void pointer
Object^ result = VoidPointerToObject(voidPtr);
return 0;
}
It crashes in the VoidPointerToObject method on calling PtrToStructure , with the error: The specified structure must be blittable or have layout information
I know this is an odd thing to do, but it is a situation I have encountered a few times, especially when unmanaged code makes a callback to managed code and passes a void* as a parameter.
(original explanation below)
If you need to pass a managed handle as a void* through native code, you should use
void* voidPtr = GCHandle::ToIntPtr(GCHandle::Alloc(o)).ToPointer();
// ...
GCHandle h = GCHandle::FromIntPtr(IntPtr(voidPtr));
Object^ result = h.Target;
h.Free();
(or use the C++/CLI helper class gcroot)
Marshal::PtrToStructure works on value types.
In C++/CLI, that means value class or value struct. You are using ref struct, which is a reference type despite use of the keyword struct.
A related problem:
void* voidPtr = &myData;
doesn't point to the object, it points to the handle.
In order to create a native pointer to data on the managed heap, you need to use pinning. For this reason, conversion between void* and Object^ isn't as useful as first glance suggests.

Resources