Return_value_policy for method with void return type and optional parameter - boost-python

I have class with void method and optional argument looking like this:
class A
{
public:
void method(int par1, bool par2 = false) { ... }
};
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(method, A::method, 1, 2)
class_<A>("A")
.def("method", &A::method, return_value_policy<reference_existing_object>(),method())
;
What is correct return_value_policy in this case? I've tried to avoid return policy completely however I've received following compile error then.
'boost::mpl::vector17<RT,most_derived<Target,ClassT>::type&,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14> boost::python::detail::get_signature(RT (__cdecl ClassT::* )(T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14) volatile const,Target *)' : expects 2 arguments - 1 provided
Any suggestion appreciated.

I've scrambled few things together. Bur I realized I do not need to use BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS but rather named arguments something like:
def("method", &A::method, (arg("par1"), arg("par2") = false))

Related

Object of type 'MyClass' cannot be converted to type 'System.Object[]' C#

I've been looking into this for a couple of hours but so far haven't gotten any luck.
Here's my C# code:
myClassInstance = new MyClass("MyParam", 1);
object[] args = new object[1] { myClassInstance };
MethodInfo methodInfo = GetType().GetMethod(myMethod, BindingFlags.NonPublic | BindingFlags.Instance);
string method = (string)methodInfo.Invoke(this, args);
I have MethodInfo and System.Reflection imported. The Unity error is this:
ArgumentException: Object of type 'SystemController' cannot be converted to type 'System.Object[]'
It doesn't point to a specific line in the code, but from what I can tell it seems to be an issue with converting the myClassInstance variable to an object, which doesn't make sense to me, as I believed everything in C# inherited from System.Object.
Here is MyClass:
public class MyClass
{
public string var1;
public int var2;
public MyClass(string param1, int param2)
{
var1 = param1;
var2 = param2;
}
}
Clearly, I'm not showing the entire class, but the only difference is that there are more variables and parameters to store. Those shouldn't change anything, so I won't bore you with them. It's just a class with a constructor, not inheriting from anything.
Any help I could get with this would be greatly appreciated. Let me know if you need more info.
The error here was me trying to pass the entire object[] array into my method as a parameter when I should have only passed the contents of the array. See here:
I was doing this:
void MyMethod(object[] args) {
MyClass instance = (MyClass)args[0];
...
}
But should've done this:
void MyMethod(MyClass myClassInstance) {
...
}
After reading some more documentation and reviewing the comments above I discovered that the .Invoke() method passes what's inside the args array instead of the entire array. At least, that's my current understanding, and it's what made my code work.
Thanks for the help.

ClaiR/Rascal: Best way to list public functions?

I am parsing an C++ header file using ClaiR and want to get a list of the public functions.
visit(ast) {
case \class(_, name(n), _, decs): {
println("class name: <n>");
isPublic = true;
for (dec <- decs) {
switch(dec) {
case \visibilityLabel(\public()): {
println("Public functions");
isPublic = true;
}
case \visibilityLabel(\protected()): {
println("Protected functions");
isPublic = false;
}
case \visibilityLabel(\private()): {
println("Private functions");
isPublic = false;
}
case \simpleDeclaration(_, [\functionDeclarator([*_], [*_], name(na), [*_], [*_])]): {
if (isPublic) {
println("public function: <na>");
}
}
}
}
}
}
The above code works. But is there a better (smaller) way of acquiring the public functions?
In C++, the public/protected/private access modifiers aren't proper "modifiers" on declarations; instead, all member declarations following an access modifier (up to a possible next access modifier) have the declared visiblity (in your example, the second public: also makes myFunc4 public). It would be straightforward to implement an AST traversal to obtain members' visiblity information and add it to a new M3 table, though. Your suggestion of public void myFunc5(); is invalid syntax.
The ProblemType in the decl indicates that the first argument of the myFunc method is unresolved (likely due to a missing import). The toString of this ProblemType in the type information should not be there, though, that is a bug.
There's an M3 modifiers relation which might have the info you're looking for:
https://github.com/usethesource/rascal/blob/1514b30341525fe66cf99a64ed995052293f09d5/src/org/rascalmpl/library/analysis/m3/Core.rsc#L61
that relation can be composed with the o operator with the qualified names of your methods to see which modifiers are declared on which method
However, that relation must be extracted of course. Perhaps that still needs to be added to ClaiR?
I have some code the looks like this:
MyClass {
public:
void myFunc1();
private:
void myFunc2();
public:
void myFunc3();
void myFunc4();
m3.modifiers does not provide public/private information. I guess (have not tried), it will work for public void myFunc5();
I also see some strange errors.
<|cpp+method:///MyClass/myFunc(org.eclipse.cdt.internal.core.dom.parser.ProblemType#38270bb,unsigned.int,unsigned.int)|,virtual()>,
Is this for a type it cannot resolve (include not provided to parser)?

The '.' operator cannot be applied to operand of type 'method group'

I have this eror:
The '.' operator cannot be applied to operand of type 'method group'
(CS0023)
I know that there is a question like this, but I checked it and the problem with that was put System before the method.
I have this code
private int posCuriosidad = 0;
// Use this for initialization
void Start () {
Random();
}
public void Random(){
posCuriosidad = Random.Range(0,9);
}
but I don't know why I get the error.
That's because calling Random.X inside a method named Random will be mapped to try to invoke X on the method group of your method.
You clearly wanted to use the built-in Random type, not your own method.
Here's a couple of ways to do this:
Rename your method, "Random" is not a verb, "Randomize" is though but you should strive to make the purpose of the method clear through its name, so perhaps "RandomizePosition" would be better?
public void RandomizePosition()
{
posCuriosidad = Random.Range(0,9);
}
Explicitly refer to the built-in Random type:
UnityEngine.Random.Range(0,9);

Class in parameter of function (Arduino) does not compile

I am trying to create a simple class in C++, but I keep getting the compilation errors:
main:2: error: variable or field 'doSomething' declared void
main:2: error: 'person' was not declared in this scope
main:
class person {
public:
int a;
};
void doSomething(person joe) {
return;
}
main() and stuff would go here, but even if I include main(){}, the errors still occur. I also tried adding 2 closed parentheses after joe, but then that creates the error:
main: In function 'void doSomething(person (*)())':
main:8: error: request for member 'a' in 'joe', which is of non-class type 'person (*)()'
Any help is greatly appreciated. (I hope this isn't something really stupid I'm missing, because I've been researching for hours).
Edit: I found out this is an Arduino-specific error. This post answers it.
I found out after reading this post that a way to work around this is:
typedef struct person{
public:
int a;
};
void doSomething(void *ptr)
{
person *x;
joe = (person *)ptr;
joe->a = 3; //To set a to 3
//Everything else is normal, except changing any value of person uses "->" rather than "."
return;
}
main()
{
person larry;
doSomething(&larry);
}
So essentially it is:
-Change class to typedef struct
-in the parameter, replace newtype with void *something
-add person *x; and x = (person *)ptr; to the beginning of the function
-whenever accessing type property, use -> rather than .
I'm not a expert but when I try to do what you want to do, I do it this way:
//create an instance of my class
MyAwesomeClass myObject;
void myFunction(MyAwesomeClass& object){
//do what you want here using "object"
object.doSomething();
object.doSomethingElse();
}
void setup() {
//setup stuff here
myObject.init();
}
void loop() {
//call myFunction this way
myFunction(myObject);
}
As I said, I'm not a C++ expert but it does the job.
Hope it helps!
My guess is, you have an invalid syntax error somewhere in the declarations above "class person...". Can you copy and paste the whole file?

C# lambda expressions and lazy evaluation

One advantage of lambda expressions is that you have to evaluate a function only when you need its result.
In the following (simple) example, the text function is only evaluated when a writer is present:
public static void PrintLine(Func<string> text, TextWriter writer)
{
if (writer != null)
{
writer.WriteLine(text());
}
}
Unfortunately, this makes using the code a little bit ugly. You cannot call it with a constant or variable like
PrintLine("Some text", Console.Out);
and have to call it this way:
PrintLine(() => "Some text", Console.Out);
The compiler is not able to "infer" a parameterless function from the passed constant. Are there any plans to improve this in future versions of C# or am I missing something?
UPDATE:
I just found a dirty hack myself:
public class F<T>
{
private readonly T value;
private readonly Func<T> func;
public F(T value) { this.value = value; }
public F(Func<T> func) {this.func = func; }
public static implicit operator F<T>(T value)
{
return new F<T>(value);
}
public static implicit operator F<T>(Func<T> func)
{
return new F<T>(func);
}
public T Eval()
{
return this.func != null ? this.func() : this.value;
}
}
Now i can just define the function as:
public static void PrintLine(F<string> text, TextWriter writer)
{
if (writer != null)
{
writer.WriteLine(text.Eval());
}
}
and call it both with a function or a value.
I doubt that C# will get this feature, but D has it. What you've outlined is a suitable way to implement lazy argument evaluation in C#, and probably compiles very similarly to lazy in D, and in more pure functional languages.
All things considered, the four extra characters, plus optional white space, are not an exceptionally large price to pay for clear overload resolution and expressiveness in what is becoming a multi-paradigm strong-typed language.
The compiler is very good at inferring types, it is not good at inferring intent. One of the tricky things about all the new syntactic sugar in C# 3 is that they can lead to confusion as to what exactly the compiler does with them.
Consider your example:
() => "SomeText"
The compiler sees this and understands that you intend to create an anonymous function that takes no parameters and returns a type of System.String. This is all inferred from the lambda expression you gave it. In reality your lambda gets compiled to this:
delegate {
return "SomeText";
};
and it is a delegate to this anonymous function that you are sending to PrintLine for execution.
It has always been important in the past but now with LINQ, lambdas, iterator blocks, automatically implemented properties, among other things it is of the utmost importance to use a tool like .NET Reflector to take a look at your code after it is compiled to see what really makes those features work.
Unfortunately, the ugly syntax is all you have in C#.
The "dirty hack" from the update does not work, because it does not delay the evaluation of string parameters: they get evaluated before being passed to operator F<T>(T value).
Compare PrintLine(() => string.Join(", ", names), myWriter) to PrintLine(string.Join(", ", names), myWriter) In the first case, the strings are joined only if they are printed; in the second case, the strings are joined no matter what: only the printing is conditional. In other words, the evaluation is not lazy at all.
Well those two statements are completely different. One is defining a function, while the other is a statement. Confusing the syntax would be much trickier.
() => "SomeText" //this is a function
"SomeText" //this is a string
You could use an overload:-
public static void PrintLine(string text, TextWriter writer)
{
PrintLine(() => text, writer);
}
You could write an extension method on String to glue it in. You should be able to write "Some text".PrintLine(Console.Out); and have it do the work for you.
Oddly enough, I did some playing with lazy evaluation of lambda expressions a few weeks back and blogged about it here.
To be honest I don't fully understand your problem, but your solutions seems a tad complicated to me.
I think a problem I solved using lambda call is similar, maybe you could use it as inspiration: I want to see if a key exists in a dictionary, if not, I would need to execute a (costly) load operation.
public static class DictionaryHelper
{
public static TValue GetValueOrLambdaDefault<TKey, TValue> (this IDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> func)
{
if (dictionary.ContainsKey(key))
return dictionary[key];
else
return func.Invoke();
}
}
[TestClass]
public class DictionaryHelperTest
{
[TestMethod]
public void GetValueOrLambdaDefaultTest()
{
var dict = new Dictionary<int, string>();
try
{
var res1 = dict.GetValueOrLambdaDefault(1, () => LoadObject());
Assert.Fail("Exception should be thrown");
}
catch { /*Exception should be thrown*/ }
dict.Add(1, "");
try
{
var res1 = dict.GetValueOrLambdaDefault(1, () => LoadObject());
}
catch { Assert.Fail("Exception should not be thrown"); }
}
public static string LoadObject()
{
throw new Exception();
}
}