TomTom wrote: |
---|
In your 'matrix_destroy' function you are passing a regular variable |
I think the double passed to matrix_destroy() is supposed to be the "disguised" pointer value returned by matrix_create(). If that is the case, the pointer value should be recoverable and delete work OK.
This approach is pretty standard, but it is a bit unusual to see a double used for the handle type. Usually I'd expect either a void* or a typed handle. It is exactly what a lot the WinAPI functions do (e.g. CreateFile, OpenProcess, ...) A handle is used to hide he underlying type (struct or class) from the client application.
@mcf3lmnfs
I hope you realise that casting a pointer to a
double is a bit unusual, and it looks rather unsafe as all your other parameters are doubles. Is there a reason you need everything to doubles? A handle type would be better here.
Actually, why are
all your parameters doubles? You can't have a 2.5 x 3.75 dimension matrix, so why aren't the number of rows and columns unsigned ints? Is this an imposed choice?
Anyway...
Your destructor code looks fine, and as unusual as it is, your matrix_destroy() should work fine as long as it's passed a valid value (i.e. one returned by matrix_create() which hasn't already been destroyed.) It might be that your trying to destroy something other than a matrix you created. To trap this track what you're new-ing and deleting, e.g.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <vector>
#include <algorithm>
#include <cassert>
#include "testdll.h"
#include "matrix.h"
#ifdef _DEBUG
std::vector<void*> alloc_ptrs;
#endif
double DLL_EXPORT matrix_create(double a,double b){
//a-stevilo vrstic
//b-stevilo stolpcev
matrix*matrika;
matrika=new matrix(a,b,0);
#ifdef _DEBUG
alloc_ptrs.push_back(matrika);
#endif
return ((double)(int) matrika);
}
double DLL_EXPORT matrix_destroy(double p){
#ifdef _DEBUG
std::vector<void*>::iterator iter
= std::find(alloc_ptrs.begin(), alloc_ptrs.end(), (matrix*)(int)p);
assert(iter != alloc_ptrs.end());
alloc_ptrs.erase(iter);
#endif
delete ((matrix*)(int)p);
return 1;
}
double DLL_EXPORT matrix_set_element(double p,double a,double b,double c){
((matrix*)(int)p)->set_element(a,b,c);
return 1;
}
double DLL_EXPORT matrix_get_element(double p,double a,double b){
return ((matrix*)(int)p)->get_element(a,b);
}
double DLL_EXPORT matrix_get_width(double p){
return ((matrix*)(int)p)->get_width();
}
double DLL_EXPORT matrix_get_height(double p){
return ((matrix*)(int)p)->get_height();
}
|
The same kind of code I'm using to check that the recovered pointer corresponds to a known matrix instance before deleting it could also be added to the other API calls the check that a valid matrix is being used with them.
Andy