Calling a function from a header in Visual C++ 2010 - c++-cli

I'm programming in Visual C++ 2010. I've got a example.h example.cpp and Form1.h.
Basically, I've pasted bits of code. I'm not able to include Form1.h in the example.h file, not sure why. But The main question is how do I call Test (which is in form1.h) from example.cpp? What would be the syntax? Is it possible to do this?
My Form1.h
#include "example.h"
public ref class Form1 : public System::Windows::Forms::Form
{
public: void Test(void)
{
// Does something
}
}
My example.cpp
#include "example.h"
#include "Form1.h"
Test(); // would like to call Test from here.

You have two problems here:
You must call functions from inside of another function. The code you currently have in your example.cpp file is invalid, because you are trying to call the Test() function at global scope.
Make it look like this instead:
int main()
{
Test();
return 0;
}
This also solves the problem that you don't have a main function, which is the entry point to any C++ application.
More generally, I would strongly recommend using one of the project templates that comes with Visual Studio to get started (rather than copying and pasting random bits of code, like you said). That ensures that you have all of the things you need to get started, like an entry point. Once you have a solid foundation, you can start building up from there.
You might also find it useful to obtain either a book on C++/CLI or an online tutorial (such as this one: Hello C++/CLI, Part 1 and Hello C++/CLI, Part 2).
Your Test function is a member function of the Form1 class, which means that you need an object of that class in order to call it. Thus, the code should actually look like this:
int main()
{
Form1^ frm = gcnew Form1();
frm.Test();
return 0;
}
Alternatively, you could work around this by making the Test() function a static function. This would allow you to call it without having an instance of the class:
public ref class Form1 : public System::Windows::Forms::Form
{
public: static void Test(void)
{
// Does something
}
}
// ...
int main()
{
Form1::Test();
return 0;
}
However, beware that this means you cannot access any other members of the Form1 class inside of the Test() function (because there is no this pointer).
This should all be explained in whatever book/tutorial you decide to use to learn C++/CLI—search for a chapter about "Classes" or "Object-Oriented Design".

Related

Monkey Patching in C#

Is it possible to extend or modify the code of a C# class at runtime?
My question specifically revolves around Monkey Patching / Duck Punching or Meta Object Programming (MOP), as it happens in scripting languages such as Groovy, Ruby etc.
For those still stumbling on this question in the present day, there is indeed a present-day library called Harmony that relatively-straightforwardly enables such monkey-patching at runtime. Its focus is on video game modding (particularly games built with Unity), but there ain't much stopping folks from using it outside of that use case.
Copying the example from their introduction, if you have an existing class like so:
public class SomeGameClass
{
public bool isRunning;
public int counter;
private int DoSomething()
{
if (isRunning)
{
counter++;
}
return counter * 10;
}
}
Then Harmony can patch it like so:
using HarmonyLib;
using Intro_SomeGame;
public class MyPatcher
{
// make sure DoPatching() is called at start either by
// the mod loader or by your injector
public static void DoPatching()
{
var harmony = new Harmony("com.example.patch");
harmony.PatchAll();
}
}
[HarmonyPatch(typeof(SomeGameClass))]
[HarmonyPatch("DoSomething")]
class Patch01
{
static AccessTools.FieldRef<SomeGameClass, bool> isRunningRef =
AccessTools.FieldRefAccess<SomeGameClass, bool>("isRunning");
static bool Prefix(SomeGameClass __instance, ref int ___counter)
{
isRunningRef(__instance) = true;
if (___counter > 100)
return false;
___counter = 0;
return true;
}
static void Postfix(ref int __result)
{
__result *= 2;
}
}
Here, we have a "prefix" patch which gets inserted before the original method runs, allowing us to set variables within the method, set fields on the method's class, or even skip the original method entirely. We also have a "postfix" patch which gets inserted after the original method runs, and can manipulate things like the return value.
Obviously this ain't quite as nice as the sorts of monkey-patching you can do in e.g. Ruby, and there are a lot of caveats that might hinder its usefulness depending on your use case, but in those situations where you really do need to alter methods, Harmony's a pretty proven approach to doing so.
Is it possible to extend or modify the code of a C# class at run-time?
No it is not possible to do this in .NET. You could write derived classes and override methods (if they are virtual) but you cannot modify an existing class. Just imagine if what you were asking was possible: you could modify the behavior of some existing system classes like System.String.
You may also take a look at Extension methods to add functionality to an existing class.
You can add functionality, but you cannot change or remove functionality.
You can extend classes by adding extra methods, but you cannot override them because added methods have always lower priority than existing ones.
For more info, check Extension Methods in C# Programming Guide.

Cannot use managed event/objects in unmanaged code error c3265, c2811

Native C++ library that I am using in C++/CLI project raises events giving me results,
If I try to handle the event by extending the unmanaged event, it says the ref class can only extend ref class.
I then tried to create a native event but have manged object inside it to collect the results, but I get the error cannot declare managed object in unmanaged class.
Is there anyway to get it done in one of the ways I am trying, or should I declare unmanaged result objects fill them in unmanaged event and then Marshall it ?
Edit:
class MyNativeListener: public NativeEventListener
{
private:
ManagedResultsObject ^_results;
public:
void onEndProcessing(ProcessingEvent *event)
{
_results.Value = event->value;
//Many more properties to capture
}
};
This is what I am trying, I have extended the native event listener to capture the event, but not sure how to capture the results to a managed object.
Edit2
Found this while searching on the same line as suggested by #mcdave auto_gcroot
Your native class needs to store a handle to the managed object instead of a reference to it. You can do this using the gcroot template. If you dig into the gcroot template you will find it uses the GCHandle Structure, which with appropriate static casting can be stored as a void* pointer and so provides a means of storing managed references in native code.
Try expanding your code along the following lines:
#include <vcclr.h>
class MyNativeListener: public NativeEventListener
{
private:
gcroot<ManagedResultsObject^> _results;
public:
void onEndProcessing(ProcessingEvent *event)
{
_results->Value = event->value;
//Many more properties to capture
}
};

How to define a macro that retains its scope after it's been called

I'm trying to make a macro to make it easier to define properties.
Simplified example but at the moment I have this to provide a property with a public get and private set:
#define propertyRO(xxType, xxName)\
property xxType xxName\
{\
xxType get() {return m___##xxName;}\
void set(xxType value) {m___##xxName = value;}\
}\
private:\
xxType m___##xxName;\
and then to use it you would do this:
public ref class Wawawa
{
public:
int bob;
propertyRO(String^, MyName);
};
This would potentially work great, but it's flawed because the member is specified in private scope, which means anything that occurs after the macro also gets private scope. e.g:
public ref class Wawawa
{
public:
int bob;
propertyRO(String^, MyName);
int fred; //ERROR HERE <- this would be private not public
};
So if you ignore what this macro actually does, my real question is: is there any way to use the private: keyword in a macro, without it affecting the rest of the class?
Insert your property macro calls all together at the end of the class defintion. (And I agree, that this answer is kind of lame ;))
I would answer: just don't do this. Don't use macros to generate code. It looks like it's going to save you time and effort, but you've already found that the macro has a problem, which is certainly not obvious to someone reading the class declaration. You may also soon find that debugging it is a nightmare, since the debugger just points at the macro line, not the code inside it.
IMO, bite the bullet and just write out all the properties in full.
I have a feeling this isn't going to be possible.
So maybe a better proposal would be to rename the macro to publicPropertyRO, which would make it obvious it will create a public property. And move the private member to be above the property declaration:
#define publicPropertyRO(xxType, xxName)\
private:\
xxType m___##xxName;\
public:\
property xxType xxName\
{\
xxType get() {return m___##xxName;}\
void set(xxType value) {m___##xxName = value;}\
}\
This would then leave the class in a public: state, which I think is acceptable.
Not really answered my question, but at least it's an improvement.
The core of the problem is that the propertyRO macro changes the scope under the hood, right? The problem is not that it changes scope per se, but that it is done in a hidden way, so the best way to handle this is to expose it.
Demoncodemonkey's suggestion is to embed public into the name of the function (which might be OK), but an alternative is to make the scope following the macro a parameter. E.g.
#define propertyRO(xxType, xxName, xxFollowingScope)\
property xxType xxName\
{\
xxType get() {return m___##xxName;}\
void set(xxType value) {m___##xxName = value;}\
}\
private:\
xxType m___##xxName;\
xxFollowingScope:
...
public ref class Wawawa
{
public:
int bob;
propertyRO(String^, MyName, public);
int fred; // No error here, fred is public
};
The syntax and naming is not super good, but it makes sure that it is not possible to use this macro without consciously making a decision about what the scope should be after the function.

What is the real significance(use) of polymorphism

I am new to OOP. Though I understand what polymorphism is, but I can't get the real use of it. I can have functions with different name. Why should I try to implement polymorphism in my application.
Classic answer: Imagine a base class Shape. It exposes a GetArea method. Imagine a Square class and a Rectangle class, and a Circle class. Instead of creating separate GetSquareArea, GetRectangleArea and GetCircleArea methods, you get to implement just one method in each of the derived classes. You don't have to know which exact subclass of Shape you use, you just call GetArea and you get your result, independent of which concrete type is it.
Have a look at this code:
#include <iostream>
using namespace std;
class Shape
{
public:
virtual float GetArea() = 0;
};
class Rectangle : public Shape
{
public:
Rectangle(float a) { this->a = a; }
float GetArea() { return a * a; }
private:
float a;
};
class Circle : public Shape
{
public:
Circle(float r) { this->r = r; }
float GetArea() { return 3.14f * r * r; }
private:
float r;
};
int main()
{
Shape *a = new Circle(1.0f);
Shape *b = new Rectangle(1.0f);
cout << a->GetArea() << endl;
cout << b->GetArea() << endl;
}
An important thing to notice here is - you don't have to know the exact type of the class you're using, just the base type, and you will get the right result. This is very useful in more complex systems as well.
Have fun learning!
Have you ever added two integers with +, and then later added an integer to a floating-point number with +?
Have you ever logged x.toString() to help you debug something?
I think you probably already appreciate polymorphism, just without knowing the name.
In a strictly typed language, polymorphism is important in order to have a list/collection/array of objects of different types. This is because lists/arrays are themselves typed to contain only objects of the correct type.
Imagine for example we have the following:
// the following is pseudocode M'kay:
class apple;
class banana;
class kitchenKnife;
apple foo;
banana bar;
kitchenKnife bat;
apple *shoppingList = [foo, bar, bat]; // this is illegal because bar and bat is
// not of type apple.
To solve this:
class groceries;
class apple inherits groceries;
class banana inherits groceries;
class kitchenKnife inherits groceries;
apple foo;
banana bar;
kitchenKnife bat;
groceries *shoppingList = [foo, bar, bat]; // this is OK
Also it makes processing the list of items more straightforward. Say for example all groceries implements the method price(), processing this is easy:
int total = 0;
foreach (item in shoppingList) {
total += item.price();
}
These two features are the core of what polymorphism does.
Advantage of polymorphism is client code doesn't need to care about the actual implementation of a method.
Take look at the following example.
Here CarBuilder doesn't know anything about ProduceCar().Once it is given a list of cars (CarsToProduceList) it will produce all the necessary cars accordingly.
class CarBase
{
public virtual void ProduceCar()
{
Console.WriteLine("don't know how to produce");
}
}
class CarToyota : CarBase
{
public override void ProduceCar()
{
Console.WriteLine("Producing Toyota Car ");
}
}
class CarBmw : CarBase
{
public override void ProduceCar()
{
Console.WriteLine("Producing Bmw Car");
}
}
class CarUnknown : CarBase { }
class CarBuilder
{
public List<CarBase> CarsToProduceList { get; set; }
public void ProduceCars()
{
if (null != CarsToProduceList)
{
foreach (CarBase car in CarsToProduceList)
{
car.ProduceCar();// doesn't know how to produce
}
}
}
}
class Program
{
static void Main(string[] args)
{
CarBuilder carbuilder = new CarBuilder();
carbuilder.CarsToProduceList = new List<CarBase>() { new CarBmw(), new CarToyota(), new CarUnknown() };
carbuilder.ProduceCars();
}
}
Polymorphism is the foundation of Object Oriented Programming. It means that one object can be have as another project. So how does on object can become other, its possible through following
Inheritance
Overriding/Implementing parent Class behavior
Runtime Object binding
One of the main advantage of it is switch implementations. Lets say you are coding an application which needs to talk to a database. And you happen to define a class which does this database operation for you and its expected to do certain operations such as Add, Delete, Modify. You know that database can be implemented in many ways, it could be talking to file system or a RDBM server such as MySQL etc. So you as programmer, would define an interface that you could use, such as...
public interface DBOperation {
public void addEmployee(Employee newEmployee);
public void modifyEmployee(int id, Employee newInfo);
public void deleteEmployee(int id);
}
Now you may have multiple implementations, lets say we have one for RDBMS and other for direct file-system
public class DBOperation_RDBMS implements DBOperation
// implements DBOperation above stating that you intend to implement all
// methods in DBOperation
public void addEmployee(Employee newEmployee) {
// here I would get JDBC (Java's Interface to RDBMS) handle
// add an entry into database table.
}
public void modifyEmployee(int id, Employee newInfo) {
// here I use JDBC handle to modify employee, and id to index to employee
}
public void deleteEmployee(int id) {
// here I would use JDBC handle to delete an entry
}
}
Lets have File System database implementation
public class DBOperation_FileSystem implements DBOperation
public void addEmployee(Employee newEmployee) {
// here I would Create a file and add a Employee record in to it
}
public void modifyEmployee(int id, Employee newInfo) {
// here I would open file, search for record and change values
}
public void deleteEmployee(int id) {
// here I search entry by id, and delete the record
}
}
Lets see how main can switch between the two
public class Main {
public static void main(String[] args) throws Exception {
Employee emp = new Employee();
... set employee information
DBOperation dboper = null;
// declare your db operation object, not there is no instance
// associated with it
if(args[0].equals("use_rdbms")) {
dboper = new DBOperation_RDBMS();
// here conditionally, i.e when first argument to program is
// use_rdbms, we instantiate RDBM implementation and associate
// with variable dboper, which delcared as DBOperation.
// this is where runtime binding of polymorphism kicks in
// JVM is allowing this assignment because DBOperation_RDBMS
// has a "is a" relationship with DBOperation.
} else if(args[0].equals("use_fs")) {
dboper = new DBOperation_FileSystem();
// similarly here conditionally we assign a different instance.
} else {
throw new RuntimeException("Dont know which implemnation to use");
}
dboper.addEmployee(emp);
// now dboper is refering to one of the implementation
// based on the if conditions above
// by this point JVM knows dboper variable is associated with
// 'a' implemenation, and it will call appropriate method
}
}
You can use polymorphism concept in many places, one praticle example would be: lets you are writing image decorer, and you need to support the whole bunch of images such as jpg, tif, png etc. So your application will define an interface and work on it directly. And you would have some runtime binding of various implementations for each of jpg, tif, pgn etc.
One other important use is, if you are using java, most of the time you would work on List interface, so that you can use ArrayList today or some other interface as your application grows or its needs change.
Polymorphism allows you to write code that uses objects. You can then later create new classes that your existing code can use with no modification.
For example, suppose you have a function Lib2Groc(vehicle) that directs a vehicle from the library to the grocery store. It needs to tell vehicles to turn left, so it can call TurnLeft() on the vehicle object among other things. Then if someone later invents a new vehicle, like a hovercraft, it can be used by Lib2Groc with no modification.
I guess sometimes objects are dynamically called. You are not sure whether the object would be a triangle, square etc in a classic shape poly. example.
So, to leave all such things behind, we just call the function of derived class and assume the one of the dynamic class will be called.
You wouldn't care if its a sqaure, triangle or rectangle. You just care about the area. Hence the getArea method will be called depending upon the dynamic object passed.
One of the most significant benefit that you get from polymorphic operations is ability to expand.
You can use same operations and not changing existing interfaces and implementations only because you faced necessity for some new stuff.
All that we want from polymorphism - is simplify our design decision and make our design more extensible and elegant.
You should also draw attention to Open-Closed Principle (http://en.wikipedia.org/wiki/Open/closed_principle) and for SOLID (http://en.wikipedia.org/wiki/Solid_%28Object_Oriented_Design%29) that can help you to understand key OO principles.
P.S. I think you are talking about "Dynamic polymorphism" (http://en.wikipedia.org/wiki/Dynamic_polymorphism), because there are such thing like "Static polymorphism" (http://en.wikipedia.org/wiki/Template_metaprogramming#Static_polymorphism).
You don't need polymorphism.
Until you do.
Then its friggen awesome.
Simple answer that you'll deal with lots of times:
Somebody needs to go through a collection of stuff. Let's say they ask for a collection of type MySpecializedCollectionOfAwesome. But you've been dealing with your instances of Awesome as List. So, now, you're going to have to create an instance of MSCOA and fill it with every instance of Awesome you have in your List<T>. Big pain in the butt, right?
Well, if they asked for an IEnumerable<Awesome>, you could hand them one of MANY collections of Awesome. You could hand them an array (Awesome[]) or a List (List<Awesome>) or an observable collection of Awesome or ANYTHING ELSE you keep your Awesome in that implements IEnumerable<T>.
The power of polymorphism lets you be type safe, yet be flexible enough that you can use an instance many many different ways without creating tons of code that specifically handles this type or that type.
Tabbed Applications
A good application to me is generic buttons (for all tabs) within a tabbed-application - even the browser we are using it is implementing Polymorphism as it doesn't know the tab we are using at the compile-time (within the code in other words). Its always determined at the Run-time (right now! when we are using the browser.)

C++ Class read as variable, default-type int? Say what?

So, I have two classes...Very basic in structure. I try to import one into the other, and declare a new object of that class type...however, it seems to read the class name as the name of a variable?!
The header class provided below will not read the "ApplicationManager" class properly.
Code:
####ifndef _GAME_H_
####define _GAME_H_
####include "application.h"
####include "applicationmanager.h"
class Game : public Application
{
public:
Game();
~Game();
void LoadContent() override;
void UnloadContent() override;
void Draw() override;
private:
//int ApplicationManager; //WHY DOES THIS COMPILE??!
ApplicationManager management; //This DOES NOT WORK?
};
####endif
Here is the header for the "ApplicationManager" class.
Code:
####ifndef _APPMANAGER_H_
####define _APPMANAGER_H_
####include "game.h"
####include "application.h"
class ApplicationManager
{
public:
ApplicationManager(void);
~ApplicationManager(void);
private:
};
####endif
The error that occurs, tells me that I need a ";" before "management", and that "ApplicationManager" is missing a type specifier, so it is assumed to be default-type int.
...any ideas why it won't compile properly? Can someone else try this and report the results? I copied the code, and pasted it in a different solution, to see if something became corrupted....it still didn't work.
You have a cyclic reference. When game.h is included from applicationmanager.h, the ApplicationManager class has not yet been read by the compiler.
To fix, remove the line
#include "game.h"
from applicationmanager.h.
Why do you have circular dependency between Game.h and AppicationManager.h?
Aside from that, I'd say check your header guard (#ifdef _*_H) in Application.h. A fairly often occurence in C++, when copy/pasting code or copying files, is to forget to change the header guard define name for a new class, so you end up with two different headers guarded by the same define. In which case, if both are included into some other file, only the first will actually be expanded into anything useful.
THe error message is some what misleading. It basically says "For some reason (probably an error in the referenced type) I cannot recognize the type you're using (in you case ApplicationManager)".
If you need ApplicationManager to know about Game make a pure virtual base class (interface in other terms) and have Game inherit from that (with out extending the interface) and have ApplicationManager include the base class header file