How to properly printf float (*)() in objective-c? - objective-c

I have these two lines of code that which I try to printf on the console, however, in objective-C I get an error saying that: format specifies type 'double' but the argument has type 'float (*)()'
How to properly make this works in Obj-C?
SomeValue = (float (*)())dlsym(someServices, "someMethod");
printf("%f\n", someValue);
Thanks in advance!

someValue in your code is a function pointer, not a value returned from the corresponding function. If you need to print the value returned from that function, simply invoke it:
printf("%f\n", someValue());
// ^^
It goes without saying that you have to NULL-check anything that comes from dlsym.

Related

Not able to print the value of a key of a Map in Kotlin

I'm fairly new to Kotlin. I want to print the count of a character in a string. For this, I'm using Kotlin's groupingBy() function and applying eachCount() to it.
My code:
val str = "0100101101010"
val countMap : Map<Char, Int> = str.groupingBy { it }.eachCount()
println(countMap["1"])
But I'm getting this error in the console: Type inference failed. The value of the type parameter K should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly.
Can someone explain to me what I'm doing wrong here?
"1" is a string literal, but your map has characters as keys. You should use the character literal '1':
println(countMap['1'])
The reason for that confusing error message is because it is trying to call this get overload, which is generic. It tries to infer the generic type arguments, and fails.

Different variable type declaration in Golang

Hi I'm just learning Go since the last view days, read some docs and noted that its something about defining struct or interface. Still cant get the difference between
var result []Struct
and
result := Struct{}
Is there particular docs I can refer to?
The result in the first example is a nil slice. The spec says that variables are initialized to their zero values and that zero value of a slice is nil.
The result in the second example is a Struct value. It uses a short variable declaration and composite literal value for a Struct. The second example identical to
var result Struct
Perhaps you meant to write
result := []Struct{}
for the second example. This is a non-nil zero length slice. The expression []Struct{} is a composite literal for an empty slice of Struct.

Velocity template function from string literal

Is it possible to call a function that was created from string literal? For example
${object}.staticPartOfFunctionName${dynamicPartOfFunctionName}()
doesn't return correct value, but instead just prints the object and the function name.
$object.staticFunctionName()
prints correctly, and
$object.staticPartOfFunctionName${dynamicPartOfFunctionName}()
gives warning "Encountered ")"
You don't have to use introspection:
#evaluate("\$object.staticPartOfFunctionName${dynamicPartOfFunctionName}()")
Well, I found one solution myself from Java side:
$object.getClass().getMethod("staticPartOfFunctionName$dynamicPartOfFunctionName").invoke($object))
I don't know if it's any good, so if someone knows how to do it velocity way, lemme know.

Exclamation operator?

I'm learning D and have seen a lot of code like this:
ushort x = to!ushort(args[1]);
I assume this casts args[1] to ushort, but what's the difference between this and cast(ushort)?
EDIT: And what other uses does the exclamation mark operator have?
In D,
to!ushort(args[1])
is shorthand for the template instantiation
to!(ushort)(args[1])
and is similar to
to<ushort>(args[1])
in languages like C++/Java/C#.
The exclamation point is to note the fact that it's not a regular argument, but a template argument.
The notation does not use angle brackets because those are ridiculously difficult to parse correctly for a compiler (they make the grammar very context-sensitive), which makes it that much more difficult to implement a correct compiler. See here for more info.
The only other use I know about is just the unary 'not' operation (e.g. false == !true)... I can't think of any other uses at the moment.
Regarding the cast:
cast(ushort) is an unchecked cast, so it won't throw an exception if the value is out of range.
to!ushort() is a checked cast, so it throws an exception if the value is out of range.
The exclamation mark here is not an operator, it is just a token part of the explicit template instantiation syntax (described in detail here).
std.conv.to (docs) is a function template for converting between arbitrary types. It is implemented entirely in the library and has no special support in the language. It has a broader and different scope compared to the cast operator.
The to template takes two type parameters; a "to" type and a "from" type, in that order. In your example, the template is explicitly instantiated with the single type argument ushort for the "to" parameter, and a second type argument string (assuming args comes from the first parameter to main) is automatically inferred from the regular function argument passed to the function (args[1]) as the "from" parameter.
The resulting function takes a string parameter and returns a ushort parsed from that string, or throws an exception if it failed. The cast operator will not attempt this kind of high-level conversion.
Note that if there is more than one explicit template parameter, or that parameter has more than one token in it (ushort is a single keyword token), you must wrap the template parameter list in parentheses:
ushort result;
result = to!(typeof(result))(args[1]);
In this example, typeof, (, result and ) are four separate tokens and the parentheses are thus required.
To answer your last question, the ! token is also used for the unary not operator, unrelated to template instantiations:
bool yes = true;
bool no = !yes; // 'no' is false
You already got two excellent answers by jA_cOp and Merhdad. I just want answer directly to the OP question (what's the difference between this and cast(ushort)?) - The difference is that cast(ushort)args[1] will not work (you cannot cast from a string to an uint just like that), while the to!(type)(param) template knows what to do with the string and how to convert it to the primitive type.

Why is empty string transformed to "(null)"?

I have following code sample:
double t_values[FFT_SIZE];
AnsiString prefix;
double multiplier;
AutoScaleData(t_values, FFT_SIZE, prefix, multiplier);
AnsiString str;
str.printf("Voltage [%sV]", prefix);
Pretty simple isn't it?
String str is used as description for numeric values displayed in graph. For value say 0.05 V it is much more comprehensive and intuitive to say instead that "voltage is 50 mV". This is ensured through using proper prefix in this case "m". For values range <1; 1000) there is no need to add any prefix. We can for example say "voltage over this element is 50 volts" and this is perfectly understandable. I have problem that library function printf keeps adding string "(null)" when prefix is empty string for example:
"Voltage [(null)V]"
I haven't seen this type of behaviour anytime before when using Microsoft Visual Studio. Can this behaviour be somehow avoided?
Short Answer:
str.printf("Voltage [%sV]", prefix.c_str());
Detailed Answer:
AnsiString contains a single class member, a char* pointer named Data. When the string is empty, the Data pointer is NULL. The Data pointer resides at the starting memory address of the AnsiString instance.
When calling printf(), its %s specifier is expecting you to pass in a char* pointer, but you are passing in an AnsiString instance instead. That is effectively the same as passing printf() the internal AnsiString::Data pointer directly. In other words, this statement:
str.printf("Voltage [%sV]", prefix);
Is effectively the same as if you had done this instead:
str.printf("Voltage [%sV]", prefix.data());
That is why printf() outputs "(null)". You are passing it a NULL pointer to begin with.
The AnsiString::c_str() method never returns a NULL pointer. If the string is not empty, c_str() returns the AnsiString::Data pointer as-is. Otherwise, it returns a pointer to a static '\0' character instead. Either way, printf() does not receive a NULL pointer in that situation. If the string is empty, it receives a pointer to a 0-length null-terminated string, so it outputs a blank string instead of "(null)".
If is very likely that your variable prefix is NULL. Try this:
str.printf("Voltage [%sV]", prefix == NULL ? "" : prefix);
I managed to do this with following construction:
str.printf("Voltage [%sV]", prefix.c_str());
But i don't understand what is the difference.
Using the Joachim's answer, I've created the following macro (using C):
#define ISNULLSTR(x) (x == NULL ? "" : x)
And I can use it like:
printf("%s", ISNULLSTR(possible_null_text));
Hopefully it will help someone reaching here for the same reason.