How to check an object's type in C++/CLI? - c++-cli

Is there a simple way to check the type of an object? I need something along the following lines:
MyObject^ mo = gcnew MyObject();
Object^ o = mo;
if( o->GetType() == MyObject )
{
// Do somethine with the object
}
else
{
// Try something else
}
At the moment I'm using nested try-catch blocks looking for System::InvalidCastExceptions which feels ugly but works. I was going to try and profile something like the code above to see if it's any faster/slower/readable but can't work out the syntax to even try.
In case anyone's wondering, this comes from having a single queue entering a thread which supplied data to work on. Occasionally I want to change settings and passing them in via the data queue is a simple way of doing so.

You can use MyObject::typeid in C++/CLI the same way as typeof(MyObject) is used in C#. Code below shamelessly copied from your question and modified ...
MyObject^ mo = gcnew MyObject();
Object^ o = mo;
if( o->GetType() == MyObject::typeid )
{
// Do somethine with the object
}
else
{
// Try something else
}

You should check out How to: Implement is and as C# Keywords in C++:
This topic shows how to implement the functionality of the is and as C# keywords in Visual C++.

edit: I will leave this here. But this answer is for C++. Probably not even slightly related to doing this for the CLI.
You need to compile with RTTI(Run Time Type Information) on. Then look at the wikipedia article http://en.wikipedia.org/wiki/Run-time_type_information and search google for RTTI. Should work for you.
On the other hand you might want to have a virtual base class for all your data classes with a member variable that describes what type it is.

Related

Math Parser/Lexer - Token interface design

Currently working on a small pet project, a Math Parser/Lexer and eventually solver for fun/learning. I've bashed out a basic prototype and am now looking to convert this into TypeScript to clean things up. Prototype can be found here https://github.com/chips5k/math-solver-prototype for those interested.
I am trying to come up with a clean interface based approach to dealing with my Tokens. I suspect i am looking at this the wrong way, but hopefully someone can offer useful advice.
In my TS design i have several interfaces, the base interface being Token, with NumericToken and FunctionToken extending these. I then have several classes that implement these interfaces such as: AdditionToken, VariableToken, NumberToken, PiToken, SineToken etc...
My problem is that in order to work with these interfaces i end up requiring methods to check the basic type e.g isNumeric, isFunction, isVariable or alternatively a direct type === TokenFactory.NUMERIC etc... This, to me, feels wrong as it basically voids the point of using an interface. I suspect that there is a nicer/cleaner more polymorphic approach i could take but unfortunately i'm out of ideas and have been unable to find info on what i am doing.
An example of where things fall apart shows itself when attempting to solve a series of tokens:
if(t.isFunction()) {
var a = stack.unshift();
var b = stack.unshift();
if(a.isNumeric() && b.isNumeric()){
result.push(tokenFactory.create(t.evaluate<number>(a.evaluate<number>, b.evaluate<number>));
} else {
//return to stack and move on, e.g can't solve x + 1 directly
}
} else {
stack.push(t);
}
Basically looking for what is considered the ideal approach for handling a scenario like this, and i suspect it may be an alternate approach to the design.
TIA!
basic type e.g isNumeric, isFunction, isVariable or alternatively a direct type === TokenFactory.NUMERIC etc... This, to me, feels wrong
Nope. This is fairly idiomatic as the type controls what functionality is there.
E.g you will see the TypeScript checker.ts littered with check on .kind (SyntaxKind) which is at TypeScript AST nodes discriminator.
Also you might want to consider adding a visitor that is recursive e.g.
function visit(item){
if (item.addition) {
return visit(item.left) + visit(item.right)
}
if (item.literal) {
return literal.value();
}
// ETC.
}

Confusion about the Argument< T > and Variable< T > in .NET 4.0 Workflow Foundation

I am using Windows Workflow Foundation in .NET 4.0. Below is some syntax/semantic confusion I have.
I have 2 equivalent way to declare an Assign activity to assign a value to a workflow variable (varIsFreeShipping).
(1) Using XAML in the designer.
(2) Using code.
But in approach 2, the it seems I am creating a new OutArgument< Boolean > and assign value to it, not to the original Variable< Boolean> varIsFreeShipping. And OutArgument and Variable are totally different types.
So how could the value assigned to this new Argument finally reach the original Variable?
This pattern seems common in WF 4.0. Could anybody shed some light on this?
Thanks!
As a matter of fact, the second (2) method can be written just as:
Then = new Assign<bool>
{
To = varIsFreeShipping,
Value = true
}
This all works because OutArgument<T> can be initialized through a Variable<T> using an implicit operator.
In your first (1) assign, using the editor, that's what's happening behind the scene; the variable is being implicitly converted from Variable to OutArgument.
WF4 uses alot of implicit operators mainly on Activity<T> from/to Variable<T>, OutArgument<T> from/to Variable<T>, etc. If you look at it, they all represent a piece of data (already evaluated or not), that is located somewhere. It's exactly the same as in C#, for example:
public int SomeMethod(int a)
{
var b = a;
return a;
}
You can assign an argument to a variable, but you can also return that same variable as an out argument. That's what you're doing with that Assign<T> activity (using the variable varIsFreeShipping as the activity's out argument).
This answers your question?

Whole web app in C++ with DOM interaction

I have recently heard of compiling C++ code to javascript using emscripten and how, if asmjs optimizations are done, it has the potential of running applications really fast.
I have read several post, tutorial and even heard some very interesting youtube videos. I have also run the hello world example successfully.
However, I don't know the full capabilities of this approach, specially if an entire new webapp can/should be written in C++ as a whole, without glue code.
More concretely I would like to write something similar to the following C++ (as a reference not working code).
#include <window>
class ApplicationLogic : public DOMListener{
private:
int num;
public:
ApplicationLogic():num(0);
virtual void onClickEvent(DOMEventData event){
num++;
}
virtual ~ApplicationLogic(){}
}
int main(){
DOMElement but = Window.getElementById("foo");
ApplicationLogic app();
but.setOnclick(app);
}
I hope it makes clear the idea, but the goal is to achieve something similar to:
A static function that initializes the module run when the window is ready (same behaviour that gives jquery.ready()). So listeners can be added to DOM elements.
A way to interact with the DOM directly from C/C++, hence the #include <window>, basically access to the DOM and other elements like JSON, Navigator and such.
I keep thinking of Lua and how when the lua script includes a shared object (dynamic linked library) it searched for a initialize function in that .so file, and there one would register the functions available from outside the module, just exactly how the return of the function module created in asmjs acts. But I can't figure out how to emulate jquery.ready directly with C++.
As you can see I have little knowledge about asmjs, but I haven't found tutorials or similar for what I'm looking for, I have read references to standard libraries included at compile time for stdlibc, stdlibc++ and SDL, but no reference on how to manipulate the DOM from the C++ source.
what's up. I know this is an old topic, but I'm posting here in case anyone else comes here looking for the answer to this question (like I did).
Technically, yes it is possible - but with a ton of what you called "glue code", and also a good bit of JavaScript (which kind of defeats the purpose IMO). For example:
#include <emscripten.h>
#include <string>
#define DIV 0
#define SPAN 1
#define INPUT 2
// etc. etc. etc. for every element you want to use
// Creates an element of the given type (see #defines above)
// and returns the element's ID
int RegisterElement(int type)
{
return EM_ASM_INT({
var i = 0;
while (document.getElementById(i))
i++;
var t;
if ($0 == 0) t = "div";
else if ($0 == 1) t = "span";
else if ($0 == 2) t = "input";
else
t = "span";
var test = document.createElement(t);
test.id = i;
document.body.appendChild(test);
return i;
}, type);
}
// Calls document.getElementById(ID).innerHTML = text
void SetText(int ID, const char * text)
{
char str[500];
strcpy(str, "document.getElementById('");
char id[1];
sprintf(id, "%d", ID);
strcat(str, id);
strcat(str, "').innerHTML = '");
strcat(str, text);
strcat(str, "';");
emscripten_run_script(str);
}
// And finally we get to our main entry point...
int main()
{
RegisterElement(DIV); // Creates an empty div, just as an example
int test = RegisterElement(SPAN); Creates an empty SPAN, test = its ID
SetText(test, "Testing, 1-2-3"); Set the span's inner HTML
return 0; And we're done
}
I had the same question and came up with this solution, and it compiled and worked as expected. But we're basically building a C/C++ API just to do what JavaScript already does "out of the box". Don't get me wrong - from a language standpoint I'd take C++ over JavaScript any day - but I can't help but think it's not worth the development time and possible performance issues involved in a setup like this. If I were going to do a web app in C++, I would definitely use Cheerp (the new name for Duetto).
As somebody pointed out already, if you start of with a fresh codebase exclusively for the web, then duetto could be a solution. But in my opinion duetto has many drawbacks, like no C allocators, which would probably make it very hard if you want to use 3rd party libraries.
If you are using emscripten, it provides an API for all kinds of DOM events, which does pretty much exactly what you want.
emscripten_set_click_callback(const char *target, void *userData, int useCapture, int (*func)(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData));
hope this helps

Methods with multiple arguments in objective C

If you take this method call for instance(from other post)
- (int)methodName:(int)arg1 withArg2:(int)arg2
{
// Do something crazy!
return someInt;
}
Is withArg2 actually ever used for anything inside this method ?
withArg2 is part of the method name (it is usually written without arguments as methodName:withArg2: if you want to refer to the method in the documentation), so no, it is not used for anything inside the method.
As Tamás points out, withArg2 is part of the method name. If you write a function with the exact same name in C, it will look like this:
int methodNamewithArg2(int arg1, int arg2)
{
// Do something crazy!
return someInt;
}
Coming from other programming languages, the Objective-C syntax at first might appear weird, but after a while you will start to understand how it makes your whole code more expressive. If you see the following C++ function call:
anObject.subString("foobar", 2, 3, true);
and compare it to a similar Objective-C method invocation
[anObject subString:"foobar" startingAtCharacter:2 numberOfCharacters:3 makeResultUpperCase:YES];
it should become clear what I mean. The example may be contrived, but the point is to show that embedding the meaning of the next parameter into the method name allows to write very readable code. Even if you choose horrible variable names or use literals (as in the example above), you will still be able to make sense of the code without having to look up the method documentation.
You would call this method as follows:
int i=[self methodName:arg1 withArg2:arg2];
This is just iOs's way of making the code easier to read.

Use UUID as action parameters in Play Framework

I'd like to use UUID as action parameters. However, unless I use .toString() on the UUID objects when generating the action URL's, Play seems to serialize the object differently; Something like this: referenceId.sequence=-1&referenceId.hashCode=1728064460&referenceId.version=-1&referenceId.variant=-1&referenceId.timestamp=-1&referenceId.node=-1
However, using toString "works", but when I redirect from one action to another by simply invoking the method directly, there's no way I can call toString, as the method expects a UUID. Therefore it gives me the representation shown above.
Is there any way I can intersect the serialization of a certain type?
aren't you able to just use string in your action parameter? you know that this string is an UUID, so you can always recreate UUID from it. Maybe this is not the solution for you but that's my first thought. As far as I know play serializes objects like that when passing them trough paremeters.
If this does not work for you try finding something here: http://www.playframework.org/documentation/1.2.4/controllers
I found a way to do this, but right now it means hacking a part of the frameworks code itself.
What you basically need is a TypeBinder for binding the value from the String to the UUID
and a small code change in
play/framework/src/play/data/binding/Unbinder.java
if (!isAsAnnotation) {
// We want to use that one so when redirecting it looks ok. We could as well use the DateBinder.ISO8601 but the url looks terrible
if (Calendar.class.isAssignableFrom(src.getClass())) {
result.put(name, new SimpleDateFormat(I18N.getDateFormat()).format(((Calendar) src).getTime()));
} else {
result.put(name, new SimpleDateFormat(I18N.getDateFormat()).format((Date) src));
}
}
}
//here's the changed code
else if (UUID.class.isAssignableFrom(src.getClass()))
{
result.put(name, src.toString());
}
else {
// this code is responsible for the behavior you're seeing right now
Field[] fields = src.getClass().getDeclaredFields();
for (Field field : fields) {
if ((field.getModifiers() & BeanWrapper.notwritableField) != 0) {
// skip fields that cannot be bound by BeanWrapper
continue;
}
I'm working with the framework authors on a fix for this. will come back later with results.
if you need this urgently, apply the change to the code yourself and rebuild the framework by issuing
ant
in the playframework/framework
directory.