What does it mean to write `static void * ptr = &ptr` in Objective-C - objective-c

I am reading Apple's recently (Dec 5, 2013) updated sample code for camera control using AV Foundation (here is the link). And I come across the following lines in the file AVCamViewController.m which I don't understand.
static void * CapturingStillImageContext = &CapturingStillImageContext;
static void * RecordingContext = &RecordingContext;
static void * SessionRunningAndDeviceAuthorizedContext = &SessionRunningAndDeviceAuthorizedContext;
What does it mean to assign the pointer of itself? Why do we need this?
Update (2015-10-02): Now the AVCam is updated and rename to AVCam-iOS, if you are still insterest in this code AVCamViewController.m.

Well, so idea for these constants is to have some unique value, that will not repeat anywhere in the program, but we don't really care about its content.
Now, instead of coming up with some random string/number etc, we just create a pointer, and put its address as content, this way it's unique and the code is simple is nice :)

Related

C++/CLI method calls native method to modify int - need pin_ptr?

I have a C++/CLI method, ManagedMethod, with one output argument that will be modified by a native method as such:
// file: test.cpp
#pragma unmanaged
void NativeMethod(int& n)
{
n = 123;
}
#pragma managed
void ManagedMethod([System::Runtime::InteropServices::Out] int% n)
{
pin_ptr<int> pinned = &n;
NativeMethod(*pinned);
}
void main()
{
int n = 0;
ManagedMethod(n);
// n is now modified
}
Once ManagedMethod returns, the value of n has been modified as I would expect. So far, the only way I've been able to get this to compile is to use a pin_ptr inside ManagedMethod, so is pinning in fact the correct/only way to do this? Or is there a more elegant way of passing n to NativeMethod?
Yes, this is the correct way to do it. Very highly optimized inside the CLR, the variable gets the [pinned] attribute so the CLR knows that it stores an interior pointer to an object that should not be moved. Distinct from GCHandle::Alloc(), pin_ptr<> can do it without creating another handle. It is reported in the table that the jitter generates when it compiles the method, the GC uses that table to know where to look for object roots.
Which only ever matters when a garbage collection occurs at the exact same time that NativeMethod() is running. Doesn't happen very often in practice, you'd have to use threads in the program. YMMV.
There is another way to do it, doesn't require pinning but requires a wee bit more machine code:
void ManagedMethod(int% n)
{
int copy = n;
NativeMethod(copy);
n = copy;
}
Which works because local variables have stack storage and thus won't be moved by the garbage collector. Does not win any elegance points for style but what I normally use myself, estimating the side-effects of pinning is not that easy. But, really, don't fear pin_ptr<>.

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

Managed array in VC++

I want to pass a managed array from VB.NET to a function in a VC++ project. How would I declare my C++ function and how would I use the array when I'm inside it? Specifically, I want to make VB compatible functions like the one below, which is written in plain old C.
void Vcopy(double *A, double *B)
{
int n;
for(n=0;n<3;n++)
{
B[n]=A[n];
}
}
Maybe some kind soul could convert this to something that would play nicer with VB. Thanks!
Can the C++ method be managed, e.g., C++/CLI ?
If so, then:
void Vcopy(array<double> ^A, array<double> ^B)
By the way, the rest of the method should be identical, provided that the size is 3 - otherwise use A->Length and B->Length.

Javaflow Continuation: Trying to Save Static variable

I had been trying to create some check-pointing solutions using Javaflow . It works well with all the local variable. But it is unable to save the static variable instance. I am trying to do something like this:
foo( ){
//Doing Something
//Writing the static variable value, suppose
MyClass.StaticValue=10;
Continuation.suspend( ); //Checkpoint P created
//Do Something
//Update the static value, suppose
MyClass.StaticValue=11;
return;
}
Now when i try to restore back from checkPoint P, I expect to read the StaticValue as 10, but it is 11. I have two questions regarding it:
Is it a expected behavior from Javaflow or I am missing something while using Javaflow?
Is there a smart way to store these static variable other than using some versioning and storing all of them.
I think I found my answer:
1. Javaflow don't support static variables check-pointing.
2. Only versioning looks like a direction.

Description format for an embedded structure

I have a C structure that allow users to configure options in an embedded system. Currently the GUI we use for this is custom written for every different version of this configuration structure. What I'd like for is to be able to describe the structure members in some format that can be read by the client configuration application, making it universal across all of our systems.
I've experimented with describing the structure in XML and having the client read the file; this works in most cases except those where some of the fields have inter-dependencies. So the format that I use needs to have a way to specify these; for instance, member A must always be less than or equal to half of member B.
Thanks in advance for your thoughts and suggestions.
EDIT:
After reading the first reply I realized that my question is indeed a little too vague, so here's another attempt:
The embedded system needs to have access to the data as a C struct, running any other language on the processor is not an option. Basically, all I need is a way to define metadata with the structure, this metadata will be downloaded onto flash along with firmware. The client configuration utility will then read the metadata file over RS-232, CAN etc. and populate a window (a tree-view) that the user can then use to edit options.
The XML file that I mentioned tinkering with was doing exactly that, it contained the structure member name, data type, number of elements etc. The location of the member within the XML file implicitly defined its position in the C struct. This file resides on flash and is read by the configuration program; the only thing lacking is a way to define dependencies between structure fields.
The code is generated automatically using MATLAB / Simulink so I do have access to a scripting language to help with the structure creation. For example, if I do end up using XML the structure will only be defined in the XML format and I'll use a script to create the C structure during code generation.
Hope this is clearer.
For the simple case where there is either no relationship or a relationship with a single other field, you could add two fields to the structure: the "other" field number and a pointer to a function that compares the two. Then you'd need to create functions that compared two values and return true or false depending upon whether or not the relationship is met. Well, guess you'd need to create two functions that tested the relationship and the inverse of the relationship (i.e. if field 1 needs to be greater than field 2, then field 2 needs to be less than or equal to field 1). If you need to place more than one restriction on the range, you can store a pointer to a list of function/field pairs.
An alternative is to create a validation function for every field and call it when the field is changed. Obviously this function could be as complex as you wanted but might require more hand coding.
In theory you could generate the validation functions for either of the above techniques from the XML description that you described.
I would have expected you to get some answers by now, but let me see what I can do.
Your question is a bit vague, but it sounds like you want one of
Code generation
An embedded extension language
A hand coded run-time mini language
Code Generation
You say that you are currently hand tooling the configuration code each time you change this. I'm willing to bet that this is a highly repetitive task, so there is no reason that you can't write program to do it for you. Your generator should consume some domain specific language and emit c code and header files which you subsequently build into you application. An example of what I'm talking about here would be GNU gengetopt. There is nothing wrong with the idea of using xml for the input language.
Advantages:
the resulting code can be both fast and compact
there is no need for an interpreter running on the target platform
Disadvantages:
you have to write the generator
changing things requires a recompile
Extension Language
Tcl, python and other languages work well in conjunction with c code, and will allow you to specify the configuration behavior in a dynamic language rather than mucking around with c typing and strings and and and...
Advantages:
dynamic language probably means the configuration code is simpler
change configuration options without recompiling
Disadvantages:
you need the dynamic language running on the target platform
Mini language
You could write your own embedded mini-language.
Advantages:
No need to recompile
Because you write it it will run on your target
Disadvantages:
You have to write it yourself
How much does the struct change from version to version? When I did this kind of thing I hardcoded it into the PC app, which then worked out what the packet meant from the firmware version - but the only changes were usually an extra field added onto the end every couple of months.
I suppose I would use something like the following if I wanted to go down the metadata route.
typedef struct
{
unsigned char field1;
unsigned short field2;
unsigned char a_string[4];
} data;
typedef struct
{
unsigned char name[16];
unsigned char type;
unsigned char min;
unsigned char max;
} field_info;
field_info fields[3];
void init_meta(void)
{
strcpy(fields[0].name, "field1");
fields[0].type = TYPE_UCHAR;
fields[0].min = 1;
fields[0].max = 250;
strcpy(fields[1].name, "field2");
fields[1].type = TYPE_USHORT;
fields[1].min = 0;
fields[1].max = 0xffff;
strcpy(fields[2].name, "a_string");
fields[2].type = TYPE_STRING;
fields[2].min = 0 // n/a
fields[2].max = 0 // n/a
}
void send_meta(void)
{
rs232_packet packet;
memcpy(packet.payload, fields, sizeof(fields));
packet.length = sizeof(fields);
send_packet(packet);
}