fftw_complex is the type fftw library uses for inputs and outputs. http://www.fftw.org/doc/Complex-numbers.html
can I simply use double (*input)[2]=new double [length][2];and then cast it into fftw_complex ? Would there be any incompatibility?
This would be good to know because if there would be incompatibility that would mean I'd need to create a new array of fftw_complex and copy everything to it, right?
Yes, you can use it like this:
double (*input)[2] = new double [length][2];
fftw_complex* data;
data = input;
С++ type system don't distinguish type and his typedef alias.
Function of typedef is only making type names more readable.
Related
Very simply, I’m using an optimization library in C++ that takes in a function of a single variable. I would like to be able to pass in multiple parameters though (which this library does not support). What I would like to do is create a lambda function of the sort (kind of like in Python) that lets me represent the cost function as a function of a single variable that passes in two parameters.
Here’s a simplified version of what I’m going for in pseudocode. Any help would be much appreciated. I can’t seem to get this to work with lambda in C++.
Optimize comes from a library (asa047). The version I wrote here isn’t at all realistic, but is just meant to demonstrate what this function takes in.
double cost(double x, double param1, double param2){
return x*param1 + param2;
}
double optimize(double fn( double x), double initial_value){
return optimal_x;
}
int main(){
double param1 = 2;
double param2 = 3;
function_object f; //What I would like to create
f(double x){
return cost(x,param1,param2);
}
optimize(f,2);
}
What I could see under the link to the asa47 library is that the function comes with source code. That means you can modify its parameters to pass any additional stuff as you need. I think that's the easiest and most correct way to achieve what you need. I.e. if fir example you want to additional int parameter, double fn ( double x[] ) can be replaces with something like double fn ( double x[], int p), then add int p to the "nelmin" function itself, and then modify call to fn() in the nelmin() to pass that additional p.
I'm learning C++ so this may be a basic question, however, it is a real life problem. I need to convert from a string to a double and then in turn to a double* in the most elegant/modern way possible (>C++98).
The structure is provided by a C based framework (I've simplified the code here as this is the crux of the problem only) and I cannot change the framework as this interfaces with the closed source Metatrader4 trading application (non C based). The programming interface requires a pointer to be passed to the structure.
The strings are being read from a csv file containing a dump which I have taken from the Metatrader4 application. The details of which are beyond this problem. However, the inputs remain strings hence are the origin type.
I appreciate the method used in the framework may be old skool but that's part of life. It doesn't mean that I can't aspire to do something better in my code, hence the reason I asked for elegant/modern solutions. If they don't exist then I'll be forced to use new as someone has already suggested.
I currently have the following none working code:
#include <string>
struct bidAsk
{
double *bid;
double *ask;
};
int main()
{
bidAsk ba;
ba.bid = std::stod("1.100");
ba.ask = &std::stod("1.102");
}
However, both of the above conversion methods fail with conversion errors.
The first line results in an error which states:
E0513 a value of type "double" cannot be assigned to an entity of type "double *"
The second line results in the following error:
E0158 expression must be an lvalue or a function designator
I've also tried static_cast, const_cast, make_unique and (double*) casting with no luck.
Thanks in advance.
The problem is you need some actual values for your pointers to point at. They can't just point at the temporary values returned from your number conversion functions.
struct bidAsk
{
double* bid;
double* ask;
};
int main()
{
bidAsk ba;
// these have to exist somewhere that lives as long as the
// bidAsk object that points to them.
double bid_value = std::stod("1.100");
double ask_value = std::stod("1.102");
ba.bid = &bid_value; // just pointing to the real values above
ba.ask = &ask_value;
}
As others mentioned in the comments, someone has to own the objects, the pointers are pointing at.
extern C {
struct bidAsk
{
double *bid;
double *ask;
};
}
struct BidAskWrapper
{
BidAskWrapper(const std::string& sbid, const std::string& sask)
:bid{std::stod(sbid)}, ask{std::stor(sask)}
{}
//Note: bidAsk valid only till the lifetype of the wrapper
bidAsk make_c_struct() {
return {&bid, &ask};
}
double bid, ask;
};
I have a double variable i, that is converted to a void pointer named pointer:
double i = 3;
void *pointer = &i;
When I like to convert the void pointer back to double I used:
double p = *((double*) pointer);
I would like to convert the void pointer to the type I will send as a char*:
char* myType= typeid(i).name();//get the name of type of "i"
int p = *((myType*) pointer); // how to implement?
Is it possible?
instead of
char* myType= typeid(i).name();//get the name of type of "i"
int p = *((myType*) pointer); // how to implement?
use
typedef decltype(i) myType;
myType p = *((myType*) pointer);
or better:
typedef decltype(i) myType;
auto p = *reinterpret_cast<myType*>(pointer);
Works with c++11 or later. If you want to decltype on older c++ compilers, it is emulated in boost.
Edit. This is probably different from what you wanted to do, which I suppose is something like this:
void myFunction(void* unknownParam) {
typedef (realTypeOf unknownParam) RealType; // <-- this is not real c++
RealType &a = *reinterpret_cast<RealType*>(unknownParam)
//do stuff using 'a'
}
This is not possible in C++, but there is a reason: it doesn't make much sense.
And the reason is that for myFunction to be valid the //do stuff using 'a' part should be valid for whatever type RealType ends up being. As such, it cannot rely on any feature the RealType type have: it cannot use any of its methods, it cannot use any operator, it cannot even know whether it is a class or not. Basically, you cannot do anything more with it than what you would already be able to do on a void*, so giving the type a name doesn't really help you much.
A language feature that is similar to what you want (but not quite it) is type reflection, which is not present in C++, but you can find it in language such as Java, Objective-C or C#. Basically, you ask the object itself if it has a certain method, and eventually call it. An example in Objective-C
-(void)myFunction:(id)unknownParam {
if([unknownParam respondsToSelector:#selector(myMethod)])
[unknownParam performSelector:#selector(myMethod)]
}
C/C++ does not work well to interchange datatype like for example JavaScript variables
Format of int value will be different than double value format (floating point) in binary
You cannot get original data type using typeid after it has been casted to void*. Also note that typeid will have different output on different OS and compilers
double dValue = 77.7;
void* pValue = &dValue;
//output "pV" / pointer void (depending on compiler and OS)
std::cout << typeid(dValue).name() << std::endl;
To cast from void* using string you can make rules like following. Or you can try to use C++ template functions in specific cases.
int iOutValue = 0;
double dOutValue = 0;
char* name = "double";
if(!strcmp(name, "int"))
{
iOutValue = *((int*)pValue);
}
else if(!strcmp(name, "double"))
{
dOutValue = *((double*)pValue);
}
If instead of passing around void* you used some kind of variant type, you would be able to convert it back.
If you use a string to indicate the type you will need some kind of map from string to actual type. Although you can go from type to string, there is no conversion back.
Assuming you know your underlying data is always numeric in some way, there are ways to have special discrete variants that only contain numbers. The simplest would be to store a union of a 64-bit int and a double, and some flag indicating which one you have, and then a method to convert to any numeric type, asDouble(), asLong() etc.
I have a function that takes a pointer to a floating point array. Based on other conditions, I know that pointer is actually pointing to a 2x2 OR 3x3 matrix. (in fact the memory was initially allocated as such, e.g. float M[2][2] ) The important thing is I want to make this determination in the function body, not as the function argument.
void calcMatrix( int face, float * matrixReturnAsArray )
{
// Here, I would much rather work in natural matrix notation
if( is2x2 )
{
// ### cast matrixReturnAsArray to somethingAsMatrix[2][2]
somethingAsMatrix[0][1] = 2.002;
// etc..
}
else if(is3x3)
{ //etc...
}
}
I am aware that I could use templates and other techniques to better address this problem. My question is really about how to make such a cast at the ### comment. Working in C++.
float (*somethingAsMatrix)[2] = (float (*)[2]) matrixReturnAsArray;
float * could point to the first element of an array of floats, and ought to be reinterpret_castable to that array type. And the result of that cast could point to the first element of a float [][] and so should be reinterpret_castable to that type, and so on. You ought to be able to compose such casts and just directly do
float (&arr)[2][2] = *reinterpret_cast<float (*)[2][2]>(matrixReturnAsArray);
An argument of the type float ** is not the same and should not be used this way.
To avoid undefined behavior the pointer must originate from an actual multi-dimensional array, and if the float* is used directly you cannot access more than the first row of the multi-dimensional matrix.
void foo(float *f) {
f[3] = 10.;
float (&arr)[2][2] = *reinterpret_cast<float (*)[2][2]>(f);
arr[1][1] = 10.;
}
void main() {
float a[2][2];
foo(&a[0][0]); // f[3] = 10.; is undefined behavior, arr[1][1] = 10. is well defined
float b[4];
foo(&b[0]); // f[3] = 10.; is well-defined behavior, arr[1][1] = 10. is undefined
}
Given float arr[2][2]; nothing guarantees that &arr[0][1] + 1 is the same as &arr[1][0], as far as I have been able to determine. So although you can use a single dimensional array as a multi-dimensional array by doing f[i*width + j] you cannot treat a multi-dimensional array like a single dimensional array.
It's better to use C++'s compile-time type-safety instead of just relying on not accidentally passing the wrong thing or performing the wrong reinterpret_cast. To get type-safety using raw-arrays you should use references to the raw array type you want:
void foo(float (&f)[2][2]) {}
void foo(float (&f)[3][3]) {}
If you want to pass arrays by value you can't use raw arrays and should instead use something like std::array:
void foo(std::array<std::array<float,2>,2> f) {}
void foo(std::array<std::array<float,3>,3> f) {}
This sort of casting is always cleaner, and easier to deal with, with a judicious use of typedef:
typedef float Matrix_t[2][2];
Matrix_t* someThingAsMatrix = (Matrix_t*) matrixReturnAsArray;
If this is C++ and not C, though, you should create a matrix class. (Or better yet, look for an open source one.)
If I am right:
typedef float Matrix_t[2][2];
Matrix_t &matrix = *(Matrix_t *)matrixReturnAsArray;
or
float (&matrix2)[2][2] = *(float ( *)[2][2])matrixReturnAsArray;
In C there is only the way with the pointer
Matrix_t *someThingAsMatrix = (Matrix_t *)matrixReturnAsArray;
and access via:
(*someThingAsMatrix)[1][0] = ...
I have an HDF5 file with a compound type (int, double, double). Currently I am reading it in a single operation by storing its result in an array of structures, following the example in the documentation.
However I would prefer instead to save each of the three parts in a different array, so I would like to provide 3 pointers, (int*, double*, double*) and read the data directly in the 3 arrays without copying data.
Does anybody have a suggestion on how to do that?
I don't think it is possible directly.
You can easily copy your array of structures into three arrays in a loop:
int a[n];
double b[n], c[n];
for (int i = 0; i < n; i++)
{
a[i] = s[i].a;
b[i] = s[i].b;
c[i] = s[i].c;
}
assuming s is an array of struct { int a; double b; double c; } of (constant) size n, but I have a feeling that you are looking for a direct HDF5 way…
Clearly, an hyperslab won't work since I believe that a compound type is atomic. Anyway a compound type implies that the data is stored compound in the file so it is probably more efficient to read it that way. The only limitation with the solution I gave you is memory if your array is really large. On a modern computer that should be ok though ;)
You can define a single field in a compound type. Suppose your dataset is opened as dset with three fields "a","b","c", of LENGTH elements, then
int a[LENGTH];
double b[LENGTH], c[LENGTH];
CompType atype(sizeof(int));
atype.insertMember("a", 0, PredType::NATIVE_INT);
dset.read(a, atype);
CompType btype(sizeof(double));
btype.insertMember("b", 0, PredType::NATIVE_DOUBLE);
dset.read(b, btype);
CompType ctype(sizeof(double));
ctype.insertMember("c", 0, PredType::NATIVE_DOUBLE);
dset.read(c, ctype);
This should be doing what you asked for. Maybe you are already doing this by "reading the file three times"?