C++: Save global value to memory address - or alternative way - memory

I'm currently tweaking some pixel shader code written in C++ of a computer game. I need a way to store a global value (integer or float) in a way that it can be retrieved later (within same process). Since everything seems to be executed "statelessly" in runtime it won't help simply declaring and using a static variable (class variable) as I normally would do in this situation.
Thus I came across the idea of storing my global value to a specific memory address, and get it from there later. My problem is that I have no idea whether this is possible at all and how to do it. I read those questions but didn't find an answer so far:
Create new C++ object at specific memory address?
Pointer to a specific fixed address
Assigning A Specific Memory Address from another program, and changing it's value
Assign a value to a specific address
Is this even possible on Windows Vista or 7, and if so, how? I have no option to include any library but have to achieve anything with the built-in c++ functionality.
If not (or not easily) achievable, are there alternative ways to store some value really globally (not as class variable) such that it can be accessed by other classes/instances within the same process? Maybe some sort of session or application cache like in .NET or Java?
Any help would be appreciated.

I must admit I didnt get why static won't work in your case, so my suggestion might also not work.
Is it possible for you to simply use a singleton like this:
class VariableStorage
{
public:
int getVar(string name);
void setVar(string name, int value);
static VariableStorage* instance();
//...
protected:
VariableStorge() { static obj = 0; if(!obj) obj = new VariableStorage(); return obj; }
// ...
}

Related

Behavior of PTHREAD_MUTEX_INITIALIZER on iOS

Assuming there are a few classes, each using something like the following code to protect their area.
static pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
[..]
pthread_mutex_lock(&_mutex);
//some code
pthread_mutex_unlock(&_mutex);
The question:
Do all these classes share the same mutex (so if s/o locks the mutex no one else will be able to access the protected area). Or does every PTHREAD_MUTEX_INITIALIZER create a new mutex?
Literature seems to be ambiguous about this topic, depending on the system PTHREADS is running on.
This has nothing to do with the PTHREAD_MUTEX_INITIALIZER (or even Pthreads) and cannot be system dependent.
This is a basic C++ language question. You're using a static variable so there is only one of it. You haven't shown enough code to know if it's a static member of a class (so there's one _mutex per class type, not per object) or a global static (so there's one _mutex per file).

Using hidden properties vs. private iVars

This question is specifically focused around static libraries / frameworks; in other words, code that other people will eventually touch.
I'm fairly well versed in properties, since I started iOS development when iOS 6 was released. I have used hidden properties declared in interface extensions to do all of my "private" property work, including using readonly on public facing properties I don't want others to modify and readwrite within interface extensions.
The important thing is that I do not want other people who are using these static libraries / frameworks to be accessing these properties if I don't allow it, nor writing these properties if I let them read it.
I've known for a while that they could theoretically create their own interface extension and make my readonly properties readwrite themselves, or guess the names of hidden properties.
If I want to prevent this, should I be using ivars with the #private tag with directly declared ivars? Are there potential downfalls to doing it this way? Does it actually get me an additional measure of security, or is it a red herring?
Under ARC the only mode supported by properties and not instance variables is copy - so if you need copy use a property.
If you declare your private instance variables in the #implementation section:
#implementation MyClass
{
// private instance vars
}
then it takes serious effort to access them from outside the class. As you say accessing a "private" property just takes guessing its name - or using the library calls which tell you.
Is it worth it for security? YMMV. But its a good coding practice regardless.
Addendum
As the comment trail shows there has been much discussion over my use of serious effort.
First let's be clear: Objective-C is in the C family of languages, they all allow the programmer to just about anything they choose while staying within the language[*] - these are not the languages of choice if you want strong typing, access restrictions, etc., etc. within your code.
Second, "effort" is not an absolute measure! So maybe I should have chosen the word "obvious" to qualify it rather than "serious". To access a private property just requires the use of a standard method call where the object has type id - there is little clue in the code that the method being called is hidden. To access a private variable requires either an API call (a runtime function or KVC call) or some pointer manipulation - the resultant code looks nothing like a standard variable assignment. So its more obvious.
That said, apart from uses requiring copy, under ARC there is no good reason to use a private property when a private instance variable will do. For a private variable fred compare:
self.fred = 42; // property access, may involve a call (if not optimised out)
_fred = 42; // common way to bypass the accessors and get at the underlying var
fred = 42; // direct access
Take your pick, there is no right answer, but there isn't a wrong one either - this is the realm of opinion (and that is of course an opinion ;-)). I would often pick the last one, private variable - clean & simple. However #RobNapier in his answer prefers the use of properties.
[*] Note: once you consider linking to external code, say written in assembler, all bets are of in any language. At that point you have to look at the "hardware" (real or virtual) and/or "OS" to provide protection.
You should use private ("hidden") properties here. There is no "security" risk. The "attacker" in this scenario is the caller. The caller has complete access to all memory in the process. She can access anything in your framework she wants and there is absolutely nothing you can do to stop that (nor should you). This is true in any language. You can bypass "private:" designations in C++ as well if you know what you're doing. It's all just memory at the end of the day.
It is not your job to protect yourself or your framework from the caller. You both have the same goal: correct program behavior. Your goal is to protect callers from themselves. Make it difficult for them to use your framework incorrectly and easy to use it correctly.
So, you should use the tool that leads to the most correct code. And that tool is properties, and avoiding directly ivar access except in init and dealloc.

What is the syntax for implicit cast operator in dart?

I would like to cast instances of my custom class A to int. What is the syntax of the implicit cast operator? (I thought I remembered that there is such a feature but I can't find it on the web)
int a = (new A());
You can also use as to help tell the tools "no, really, treat this object as this type".
A good example of this is when you have to deal with dart:html's querySelector() function.
FormElement form = querySelector('#sign-up') as FormElement;
In the above, the object returned by querySelector('#sign-up') is checked that it is really an instance of FormElement.
Learn more at https://www.dartlang.org/docs/dart-up-and-running/ch02.html#operators
Type annotations are not allowed to affect behavior in Dart. If you're not running in checked mode, then this:
int a = new A();
will work the same as this:
var a = new A();
at run-time. In other words, when not in checked mode, you're welcome to store your A in a variable annotated as an int, but no actual conversion takes place.
If you are running in checked mode, the first form will give you a runtime exception.
I'm not sure, but I think what you're asking for is a way to define a conversion between your class A and int that will happen automatically when "cast" to an int. No such thing exists, to my knowledge. You should simply define a method to do so. For example:
int a = new A().to_i();

Safe to use Numeric.Complex with PInvoke? (It does not have LayoutKind.Sequential)

I want to use System.Numerics.Complex in an unmanaged PInvoke scenario. Using ILSpy, I noticed it does not have a LayoutKind.Sequential attribute assigned.
/// <summary>Represents a complex number.</summary>
[Serializable]
public struct Complex : IEquatable<Complex>, IFormattable
{
private double m_real;
private double m_imaginary;
...
Is it safe to give a pointer to an Complex[] array without conversion to a native function expecting the common memory layout, ie.: Real first, imaginary second? Or could the CLR possibly disorder its real and imaginary attributes for some reason?
LayoutKind.Sequential is default for all major .NET compiler: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.layoutkind.aspx
Even if it wouldn't: theonly reason to alter the order of attributes would be for alignment issues. Since System.Numerics.Complex does only have two double members there would be no reason to exchange them. So IMO you are safe.
You are fine because this is a struct. It has an implied [StructLayout] that's sequential. Something you can see from typeof(Complex).IsLayoutSequential. The same is not true for a class, it requires an explicit declaration.
And yes, fields can get swapped in the internal representation of the object. But that won't matter since the pinvoke marshaller must marshal the object. There's an implied Marshal.StructureToPtr() built into the marshaller. Fwiw, this swapping won't happen because the packing for two doubles is already optimal. They fit without leaving any padding. So the marshaller just creates a pointer to the object and won't have to copy it.
All good news :)

If I create/assign shared memory in one function, I can use it inside the function I call after can't I?

So, if I have a device (or global) function that creates/copies some data into shared memory and I later call another device function, like so:
__global__ void a(){
__shared__ int blah=0;
fun();
}
__device__ void fun(){
blah = 1; //perform some operations
//do whatever
}
I'm a bit rusty with my CUDA, I think you might have had to "redefine" shared variable (I assume the operation checked if a shared variable of that name exists, if so assigns it) - this had the effect of creating context - so basically the variable didn't just come out of nowhere. Alternatively, if it's similar to having a global variable in standard C/C++ and I can just reference it, like I did above, it'd be great.
I am familiar with memory hierarchy, I'm just rusty on the semantics of creating/referencing memory.
Please advise on whether the above sketch would work. Thanks.
No that won't work in CUDA, any more that it would work in standard C99. Currently, the preferred method of __device__ function compilation is inline expansion (they are also compiled as standalone code objects for the Fermi architecture), but even so __device__ functions still must obey standard syntax and scope conventions of C99. So you need to pass arguments which don't have compilation unit scope by reference to __device__ functions.

Resources