How to declare a global variable in Project1.cpp and read it in Unit1.cpp ?
This question is about C++ Builder
Use extern keyword in Unit1.cpp to refer the declaration from Project1.cpp.
For example, if in Project1.cpp you have
// Global variable
int myGlobalVar;
then in Unit1.cpp you should have
extern int myGlobalVar;
However, this practice is questionable and should be avoided. Important programming principles like modularization and decoupling can be denied by the usage of the global variables.
Isn't it better to do something like this?
In Project1.h, declare a variable in the public area.
public // User declarations
__fastcall TForm1(TComponent* Owner);
double MyVar;
Then include Project1.h in Unit1.cpp and then MyVar can be accessed as
Form1->MyVar
Related
What is the difference between a and b below?
class ImmutablePoint {
const ImmutablePoint(this.x, this.y);
final int x;
final int y;
const ImmutablePoint.originA() : this(0, 0);
static const ImmutablePoint originB = const ImmutablePoint(0, 0);
}
void main() {
const a = ImmutablePoint.originA();
const b = ImmutablePoint.originB;
}
The constant variable defines and names a single value.
The const constructor defines a way to create new values.
If that constructor is invoked as const ImmutablePoint.originA() then, because of constant canonicalization, it creates the same constant value that the variable contains. However, you can also call new ImmutablePoint.originA() (with or without the new) and get a new instance which is not identical to any other point object.
A Dart constructor being const means that it can be invoked using const, not that it must.
From a literal perspective, one is a constructor and the other is a static variable. The constructor allows you to define constants, and the static variable already is a constant. That much should be fairly self-explanatory.
From a performance perspective? Both values resolve to the same constant-defined object:
const ImmutablePoint(0, 0);
Thanks to Dart's canonical constant feature, everything that references this constant class with the same values 0,0 (including other calls to ImmutablePoint.originA() or even ImmutablePoint(0, 0)) will be reduced to point to the same compile-time constant. So from a practical point of view, both the parameterless const constructor and the static const variable result in virtually identical compiled code and, therefore, performance.
(Though from a strictly nit-picky point of view, the static const might be compiled to include a static reference to the ImmutablePoint type before referencing the constant. I'm not knowledgeable enough with how Dart compiles these situations to say that for certainty, but I can tell you that even if it does happen, the performance hit for a static type reference will be in the "nanoseconds-or-less" tier of negligible. Don't micro-optimize, just use whatever approach you deem more readable or convenient.)
I'm creating a word game and I need to assign coins to a user:
firstly I've read over and over on subjects "Global variables" Unfortunately i'm not able to successfully do them.
I need to make 3 bool global variable such as btn1Pressed,btn2Pressed,btn3Pressed.
& how to make the word "coins" global of type int as well?
How is this done?
#interface MainView :
To declare global variables, you need to declare them outside of any class definition. If I have a lot of global variables, I usually put them in their own source file and call it globals.m to help keep things organized. If I only have one or two, I just declare them in the App delegate (after the #includes but before the #implementation).
int coins;
BOOL btn1Pressed;
BOOL btn2Pressed;
BOOL btn3Pressed;
// etc
Then you declare them in a common header (I use globals.h) as extern. Declare them outside of any class definition:
extern int coins;
extern BOOL btn1Pressed;
extern BOOL btn2Pressed;
extern BOOL btn3Pressed;
...
That tells the compiler that "this variable is declared elsewhere", so it knows to resolve it at link time. Include that header in any source module that needs access to those variables.
Using the keyword "extern" you can make variables global.
extern int coins = 9001; //over nine thousand!
If you mean "globals" as in "accessible everywhere in your app", you can use singletons:
http://www.galloway.me.uk/tutorials/singleton-classes/
This way you can group all such global variables in one global object.
Using Singleton pattern is the ideal way to do it.
Create your properties in YourAppdelegate.h file for your bools btn1Pressed,btn2Pressed,btn3Pressed.Further synthesize them in YourAppdelegate.m file.
Now if you want to access or change these values in any other classes
// Accessing btn1Value
BOOL checkTheValueOFButton1 = [(YourAppDelegate *)[UIApplication sharedApplication]btn1Pressed];
If you want to change the value
[(YourAppDelegate *)[UIApplication sharedApplication]setbtn1Pressed:NO];
I am having an issue with Luabind that I am unsure of how to fix without some over-simplified solution.
Luabind appears to only allow binding to functions using the __cdecl calling convention. In my current project all of the functionality exposed to extensions/plugins is exposed using __stdcall. This leaves me unable to bind the exposed objects directly and instead I have to make wrappers for the objects exposed. This would be fine but there are a lot of objects that would need to be wrapped.
For example, an object can look like this:
struct IObject
{
void __stdcall SomeFunc1( void );
void __stdcall SomeFunc2( const char* );
};
struct IObjectContainer
{
IObject* __stdcall GetObject( int );
IObject* __stdcall GetObject( const char* );
};
struct IObjectCore
{
IObjectContainer* __stdcall GetObjectContainer();
};
I don't have the option of changing the entire projects calling convention currently so I am seeing if someone has a solution to perhaps patch Luabind to work with __stdcall functions. I am not the best with templates and with boost things, so I'm personally unsure where to even start trying to add the ability to use __stdcall functions.
For reference, I am using:
Lua 5.1.4
Luabind 0.9.1
VS2010
Both Lua and Luabind are stock latest versions of their rev. (Not using Lua 5.2 for project restriction reasons, but if there is a __stdcall fix for 5.2/Luabind I will gladly take that as well.)
I could only find a fix for a very old version of Luabind to do this but the patch floating on the net still for that does not line up with the current Luabind code at all.
If there is any other information needed feel free to ask.
Sadly due to inactivity and no further answers from more searching I spoke with the project developer and have gotten the entire project stripped of __stdcall. So the bindings all work fine now via __cdecl. Not the route I wanted to take but things are working as planned now.
I faced the exact same problem when binding OpenGL (with GLEW functions) to Lua, and solved it using variadic templates.
Now if the function is global and you know its address in compile time, you can be good with something like this:
template<typename Signature>
struct wrap_known;
template<typename Ret, typename... Args>
struct wrap_known<Ret __stdcall (Args...)> {
template <Ret __stdcall functor(Args...)>
static Ret invoke(Args... arguments) {
return functor(arguments...);
}
};
// I know using macro is generally a bad idea but it's just shorter
#define wrap(f) wrap_known<decltype(f)>::invoke<f>
and then, when binding, use the macro like this:
luabind::def("Clear", wrap(glClear)),
luabind::def("Vertex4f", wrap(glVertex4f))
However, in your case, we have a bunch of member functions and not globals like above.
Here is the code for wrapping member functions with __stdcall calling convention:
template<typename Signature>
struct wrap_mem;
template<typename Sub, typename Ret, typename... Args>
struct wrap_mem<Ret(__stdcall Sub::*) (Args...)> {
template <Ret(__stdcall Sub::*functor) (Args...)>
static Ret invoke(Sub* subject, Args... arguments) {
return (subject->*functor)(arguments...);
}
};
#define wrap_member(f) wrap_mem<decltype(f)>::invoke<f>
Use it like this:
struct A {
int __stdcall my_method(double b) {
return 2;
}
};
// ...
luabind::class_<A>("A")
.def("my_method", wrap_member(&A::my_method))
Sometimes, however, you are not that lucky to know the function's address in compile time, and this happens with GLEW for example. For functions like glUniform*f, glGetUniformLocation, the "wrap" macro will not work, so I made another version for wrapping functions known at runtime:
template<typename Signature>
struct wrap_unknown;
template<typename Ret, typename... Args>
struct wrap_unknown<Ret (__stdcall*) (Args...)> {
template <Ret (__stdcall** functor)(Args...)>
static Ret invoke(Args... arguments) {
return (**functor)(arguments...);
}
};
#define wrap_ptr(f) wrap_unknown<decltype(f)>::invoke<&f>
(if above code scares you, it is actually a good sign)
Now you can bind GLEW functions like this:
luabind::def("Uniform4f", wrap_ptr(glUniform4f)),
luabind::def("GetUniformLocation", wrap_ptr(glGetUniformLocation))
Just don't ask me to write another version for binding pointers to members known at runtime :)
If you don't want to use C++11 for some reason, here you can find out how to pass function arguments and return value as template parameters in C++03.
Dart has the concept of compile-time constants. A compile-time constant is parsed and created at compile time, and canonicalized.
For example, here is a const constructor for Point:
class Point {
final num x, y;
const Point(this.x, this.y);
}
And here's how you use it:
main() {
var p1 = const Point(0, 0);
var p2 = const Point(0, 0);
print(p1 == p2); // true
print(p1 === p2); // true
}
This is a non-obvious feature, with seemingly no parallels to features in other dynamic languages. There are restrictions on const objects, like all fields must be final and it must have a const constructor.
Why does Dart have compile-time constants?
From the mailing list, Florian Loitsch writes:
The canonicalization property of compile-time constants is nice, but
not the main-reason to have them. The real benefit of compile-time
constants is, that they don't allow arbitrary execution at
construction and can therefore be used at places where we don't want
code to executed. Static variables initializers, for example, were
initially restricted to compile-time constants to avoid execution at
the top-level. In short, they make sure that a program starts with
'main' and not somewhere else.
Lasse's answer here helped me a lot
So, what are compile-time constants good for anyway?
They are useful for enums.
You can use compile-time constant values in switch cases.
They are used as annotations.
Compile-time constants used to be more important before Dart switched
to lazily initializing variables. Before that, you could only declare
an initialized global variable like "var x = foo;" if "foo" was a
compile-time constant. Without that requrirement, most programs can be
written without using any const objects
I have a module which contains an interface to a native DLL; it looks like this:
// nvtt.dll binding module
module private NvTextureTools =
type NvttInputOptions = IntPtr
[<DllImport("nvtt", CallingConvention = CallingConvention.Cdecl)>]
extern NvttInputOptions nvttCreateInputOptions()
[<DllImport("nvtt", CallingConvention = CallingConvention.Cdecl)>]
extern void nvttDestroyInputOptions(NvttInputOptions)
[<DllImport("nvtt", CallingConvention = CallingConvention.Cdecl)>]
extern void nvttSetInputOptionsAlphaMode(NvttInputOptions, AlphaMode alphaMode)
[<DllImport("nvtt", CallingConvention = CallingConvention.Cdecl)>]
extern void nvttSetInputOptionsGamma(NvttInputOptions, float inputGamma, float outputGamma)
[<DllImport("nvtt", CallingConvention = CallingConvention.Cdecl)>]
extern void nvttSetInputOptionsWrapMode(NvttInputOptions, WrapMode mode)
(there are 5x more functions, but this should give the general idea).
Is there any way to specify the DllImport parameters just once? As far as I understand, I can't inherit from DllImport (it's sealed, and anyway I don't think it would work if it was not), and I can't use reflection to add the necessary attributes because I need them at compilation time.
I could make a brand new class with P/Invoke methods using reflection, but this will make calling them cumbersome.
Any thoughts?
I don't know about F#, but in C# you can do something like:
static const string DllName = "nvtt";
[DllImport(DllName, other params...)]
some function signature
[DllImport(DllName, other params...)=
some function signature
So that way the actual string is only declared once - the DllImport attributes themselves all still look a lot alike, but it makes changing things easier. I think you could do the same with CallingConvention, but I've never tried it with an enum.
Just in case you are using Visual Studio - it is possible to create a T4 template and generate all those nasty attributes. This is not an F# or VS specific solution however, any code generating tool would work.