C functions like memcpy and memset are available as C functions as well as #define in iOS:
For example the #define memcpy, under the hood, is:
#define memcpy(dest, src, len) \
((__darwin_obsz0 (dest) != (size_t) -1) \
? __builtin___memcpy_chk (dest, src, len, __darwin_obsz0 (dest)) \
: __inline_memcpy_chk (dest, src, len))
I gather there is some memory checking here but can someone shed some additional details on why it is better than a memcpy alone (where is the value added)?
More importantly, when to use which?
Those names, such as __inline_memcpy_chk, are used by the compiler to help it optimize uses of memcpy. They are special names that corresponding to built-in features of the compiler. They assist it in converting certain uses of memcpy into code that is faster than calling the memcpy library routine. The result might be simple move instructions or, even more efficiently, simple changes of information inside the compiler, so that it knows a copy of a value is available in a register.
If you undefine the macro memcpy so that these built-in features are not used, which is permitted by the C standard, the memcpy routine will still work, but it may be less efficient than if you left it alone.
Generally, you should not try to call these internal names yourself. They have been designed and defined to make the normal use of memcpy efficient.
Unless you #undef the macro, or call it like this (memcpy)(args...), it will always use the macro variant.
I would personally just use the maco - it's intended to be fast and efficient, and will work as you expect.
To answer your questions,
1) I have no additional details, but peeking under the hood like that violates the abstraction the authors have provided for you. You want memcpy, you've got memcpy as they've provided it there, implemented with the snippet you're showing. If you're curious how it works, you can dig into it, but because you asked "when to use which" I suspect you're trying to figure out something that works in practice. Which gets to the answer to your second question...
2) You should use memcpy(dest, src, len). Don't hack around the #define and use the underlying code in a way that was not intended. You're provided with memcpy() as it is there; for you, that is memcpy.
Related
I would like to use m4 as a preprocessor for a couple of different scripting languages that lack this facility.
In particular, I need to emulate the C preprocessor (cpp) functionality of conditional code inclusion:
#if something
some
long
code
block
#else
alternate
code
block
#if something-else
do
more
stuff
#endif
#endif
m4's ifelse() does not particularly lend itself to long code blocks, so it seems I essentially need to write m4 macros to emulate this, by testing the condition and then using divert to include or exclude blocks as appropriate.
The tricky part will be keeping track of nesting levels; as far as I can tell, I will have to implement my own stack within m4 to do this. This seems conceptually straightforward, and I'm sure with a day or two of hacking I can have a working system.
But it feels like reinventing the wheel — I surely can't be the first person with this need. Existing, tested, robust solutions are surely better than whatever I can hack together as an m4 rank beginner.
Are there common m4 idioms for this? Is there existing open-source m4 code to do this? Poking around in search engines didn't turn up anything useful.
(Using cpp itself won't work for reasons given in cpp's own documentation: "It will choke on input which does not obey C's lexical rules." It seems gpp has this functionality out of the box, so using that might make more sense, but I prefer the ubiquity of m4 if it's not too painful to make m4 do this.)
I was also looking for this, and ended up writing my own. Here is a link to the code on my wiki:
http://www.eugeneweb.com/wiki/Sites/M4Macros
I defined the names without the #'s eg. IF, ELSE, ENDIF, etc... Also M4 requires parens to hold the arguments where CPP (Mostly) does not. I also added a selective invoke to protect macros with side effects from invocation in an unselected block.
Ciao.
I've an app in which I need to send a packet to an external device. This packet has a CRC before the end message. The CRC has to be separated in CRCH and CRCL.
For example: CRC = 0x5B so CRCH should be 0x35 (ASCII representation of 5) and CRCL should be 0x42 (ASCII representation of B).
I searched on internet and I found several functions in C or in other language to create CRC32, but my device need to use a CRC8. How I can create a CRC8 in Objective-C? Can you help me to find a way to do this?
Surprising how this rather simple question is still not answered.
First, you need to separate problems in your question. CRH and CRL are just hex conversion and that's easy to do (and has lots of examples on internet too). In most cases, you just need to compare crc you received to one you calculated. So, you just need to convert them to the same form. E.g. convert the crc you calculated to text using sprintf and %2X format and compare with CRC you received (as text).
The second part is actually CRC. This is a little bit trickier.Your options are as follows:
1) the easiest is to rename your .m file to .mm and use CRC library from boost C++. It's just a header include, so it won't affect rest of your code in any way and you can even make it in a separate file, so you'll have a C function which will use boost under the hood.
You might need to find parameters for your CRC though. For that, see this excellent resource http://reveng.sourceforge.net/crc-catalogue/
2) You can write your own implementation. Surprisingly there is plenty of examples for particular algorithms in the internet, but they often optimized for particular crc and are hard to adopt for other algorithms.
So, your best bet is probably starting with "A Painless Guide to CRC Error Detection Algorithms" article by Ross Williams. It also includes examples in C.
Though it could be complicated to get your head around all the technical stuff and explanations there.
So, as as short cut I'd like to suggest to look at my own implementation in java here. It's obviously not Objective-C. But I looked through it and you should be able to just copy and paste to your .m file and just compile it. Possibly adjusting few types.
You'll need public static long calculateCRC(Parameters crcParams, byte[] data) and private static long reflect(long in, int count) functions there. And the Parameters class which looks scarier, but should just become a struct in your case:
struct Parameters
{
int width; // Width of the CRC expressed in bits
long polynomial; // Polynomial used in this CRC calculation
bool reflectIn; // Refin indicates whether input bytes should be reflected
bool reflectOut; // Refout indicates whether input bytes should be reflected
long init; // Init is initial value for CRC calculation
long finalXor; // Xor is a value for final xor to be applied before returning result
}
You might also want to also adjust types there to a shorter unsigned type (java has no unsigned). But it should work perfectly well as is.
I need to do some metaprogramming on a large Mathematica code base (hundreds of thousands of lines of code) and don't want to have to write a full-blown parser so I was wondering how best to get the code from a Mathematica notebook out in an easily-parsed syntax.
Is it possible to export a Mathematica notebook in FullForm syntax, or to save all definitions in FullForm syntax?
The documentation for Save says that it can only export in the InputForm syntax, which is non-trivial to parse.
The best solution I have so far is to evaluate the notebook and then use DownValues to extract the rewrite rules with arguments (but this misses symbol definitions) as follows:
DVs[_] := {}
DVs[s_Symbol] := DownValues[s]
stream = OpenWrite["FullForm.m"];
WriteString[stream,
DVs[Symbol[#]] & /# Names["Global`*"] // Flatten // FullForm];
Close[stream];
I've tried a variety of approaches so far but none are working well. Metaprogramming in Mathematica seems to be extremely difficult because it keeps evaluating things that I want to keep unevaluated. For example, I wanted to get the string name of the infinity symbol using SymbolName[Infinity] but the Infinity gets evaluated into a non-symbol and the call to SymbolName dies with an error. Hence my desire to do the metaprogramming in a more suitable language.
EDIT
The best solution seems to be to save the notebooks as package (.m) files by hand and then translate them using the following code:
stream = OpenWrite["EverythingFullForm.m"];
WriteString[stream, Import["Everything.m", "HeldExpressions"] // FullForm];
Close[stream];
You can certainly do this. Here is one way:
exportCode[fname_String] :=
Function[code,
Export[fname, ToString#HoldForm#FullForm#code, "String"],
HoldAllComplete]
For example:
fn = exportCode["C:\\Temp\\mmacode.m"];
fn[
Clear[getWordsIndices];
getWordsIndices[sym_, words : {__String}] :=
Developer`ToPackedArray[words /. sym["Direct"]];
];
And importing this as a string:
In[623]:= Import["C:\\Temp\\mmacode.m","String"]//InputForm
Out[623]//InputForm=
"CompoundExpression[Clear[getWordsIndices], SetDelayed[getWordsIndices[Pattern[sym, Blank[]], \
Pattern[words, List[BlankSequence[String]]]], Developer`ToPackedArray[ReplaceAll[words, \
sym[\"Direct\"]]]], Null]"
However, going to other language to do metaprogramming for Mathematica sounds ridiculous to me, given that Mathematica is very well suited for that. There are many techniques available in Mathematica to do meta-programming and avoid premature evaluation. One that comes to my mind I described in this answer, but there are many others. Since you can operate on parsed code and use the pattern-matching in Mathematica, you save a lot. You can browse the SO Mathematica tags (past questions) and find lots of examples of meta-programming and evaluation control.
EDIT
To ease your pain with auto-evaluating symbols (there are only a few actually, Infinity being one of them).If you just need to get a symbol name for a given symbol, then this function will help:
unevaluatedSymbolName = Function[sym, SymbolName#Unevaluated#sym, HoldAllComplete]
You use it as
In[638]:= unevaluatedSymbolName[Infinity]//InputForm
Out[638]//InputForm="Infinity"
Alternatively, you can simply add HoldFirst attribute to SymbolName function via SetAttributes. One way is to do that globally:
SetAttributes[SymbolName,HoldFirst];
SymbolName[Infinity]//InputForm
Modifying built-in functions globally is however dangerous since it may have unpredictable effects for such a large system as Mathematica:
ClearAttributes[SymbolName, HoldFirst];
Here is a macro to use that locally:
ClearAll[withUnevaluatedSymbolName];
SetAttributes[withUnevaluatedSymbolName, HoldFirst];
withUnevaluatedSymbolName[code_] :=
Internal`InheritedBlock[{SymbolName},
SetAttributes[SymbolName, HoldFirst];
code]
Now,
In[649]:=
withUnevaluatedSymbolName[
{#,StringLength[#]}&[SymbolName[Infinity]]]//InputForm
Out[649]//InputForm= {"Infinity", 8}
You may also wish to do some replacements in a piece of code, say, replace a given symbol by its name. Here is an example code (which I wrap in Hold to prevent it from evaluation):
c = Hold[Integrate[Exp[-x^2], {x, -Infinity, Infinity}]]
The general way to do replacements in such cases is using Hold-attributes (see this answer) and replacements inside held expressions (see this question). For the case at hand:
In[652]:=
withUnevaluatedSymbolName[
c/.HoldPattern[Infinity]:>RuleCondition[SymbolName[Infinity],True]
]//InputForm
Out[652]//InputForm=
Hold[Integrate[Exp[-x^2], {x, -"Infinity", "Infinity"}]]
, although this is not the only way to do this. Instead of using the above macro, we can also encode the modification to SymbolName into the rule itself (here I am using a more wordy form ( Trott - Strzebonski trick) of in-place evaluation, but you can use RuleCondition as well:
ClearAll[replaceSymbolUnevaluatedRule];
SetAttributes[replaceSymbolUnevaluatedRule, HoldFirst];
replaceSymbolUnevaluatedRule[sym_Symbol] :=
HoldPattern[sym] :> With[{eval = SymbolName#Unevaluated#sym}, eval /; True];
Now, for example:
In[629]:=
Hold[Integrate[Exp[-x^2],{x,-Infinity,Infinity}]]/.
replaceSymbolUnevaluatedRule[Infinity]//InputForm
Out[629]//InputForm=
Hold[Integrate[Exp[-x^2], {x, -"Infinity", "Infinity"}]]
Actually, this entire answer is a good demonstration of various meta-programming techniques. From my own experiences, I can direct you to this, this, this, this and this answers of mine, where meta-programming was essential to solve problem I was addressing. You can also judge by the fraction of functions in Mathematica carrying Hold-attributes to all functions - it is about 10-15 percents if memory serves me well. All those functions are effectively macros, operating on code. To me, this is a very indicative fact, telling me that Mathematica jeavily builds on its meta-programming facilities.
The full forms of expressions can be extracted from the Code and Input cells of a notebook as follows:
$exprs =
Cases[
Import["mynotebook.nb", "Notebook"]
, Cell[content_, "Code"|"Input", ___] :>
ToExpression[content, StandardForm, HoldComplete]
, Infinity
] //
Flatten[HoldComplete ## #, 1, HoldComplete] & //
FullForm
$exprs is assigned the expressions read, wrapped in Hold to prevent evaluation. $exprs could then be saved into a text file:
Export["myfile.txt", ToString[$exprs]]
Package files (.m) are slightly easier to read in this way:
Import["mypackage.m", "HeldExpressions"] //
Flatten[HoldComplete ## #, 1, HoldComplete] &
I've ran Memory Validator on an application we're developing, and I've found that a Macro expressions we've defined is at the root of about 90% of the leaks. #define O_set.
Now, our macros are defined as follows:
#define O_SET_VALUE(ValueType, Value) boost::shared_ptr<ValueType>(new ValueType(Value))
.
.
#define O_set O_SET_VALUE
However, according to the Boost web site (at: http://www.boost.org/doc/libs/1_46_1/libs/smart_ptr/shared_ptr.htm):
A simple guideline that nearly
eliminates the possibility of memory
leaks is: always use a named smart
pointer variable to hold the result of
new. Every occurence of the new
keyword in the code should have the
form: shared_ptr p(new Y); It is,
of course, acceptable to use another
smart pointer in place of shared_ptr
above; having T and Y be the same
type, or passing arguments to Y's
constructor is also OK.
If you observe this guideline, it
naturally follows that you will have
no explicit deletes; try/catch
constructs will be rare.
This leads me to believe that this is indeed the major cause of our memory leaks. Or am I being naive or completely out of my depth here?
Question is, is there a way to work around the mentioned issue, with the above macro #defines?
Update:
I'm using them, for example, like this:
return O_set(int, 1);
_time_stamp(O_set(TO_DateTime, TO_DateTime())) (_time_stamp is a member of a certain class)
I'm working in Windows and used MemoryValidator for tracking the Memory Leaks - according to it there are leaks - as I state, the root of most of which (according to the stack traces) come down to that macro #define.
Smart pointers are tricky. The first thing I would do is to check your code for any 'new' statement which isn't inside either macro.
Then you have to think about how the pointers are being used; if you pass a smart pointer by reference, the reference counter isn't increased, for example.
Another thing to check is all instances of '.get()', which is a big problem if you are working with a legacy code base or other developers who don't understand the point of using smart pointers! (this is more to do with preventing random crashes than memory links persé, but worth checking)
Also, you might want to consider why you are using a macro for all smart pointer creation. Boost supply different smart pointers for different purposes. There isn't a one size fits all solution. Good old std::auto_ptr is fine for most uses, except storing in standard containers, but you knew that already.
The most obvious and overlooked aspect is, do you really need to 'new' something. C++ isn't Java, if you can avoid creating dynamic objects you are better off doing so.
If you are lucky enough to be working with a *NIX platform (you don't mention, sorry) then try the leak checking tool with Valgrind. It's very useful. There are similar tools available for windows, but often using you're software skilz is best.
Good luck.
can any one please say what is use of inline keyword in delphi
It is a hint to the compiler that the function/procedure should be (if possible) inlined, ie when you call it it should be expanded like a macro instead of being called.
This is an optimization for (very) small functions where the overhead of a call would be significant. You will find many examples in for example windows.pas
What actually happens depends on the complexity of the function, public/private access and your Delphi version.
It tells the compiler to generate code for the inline; routine on the place where it is called, instead of jumping to the routine and back.
For procedures that translate to very short assembler, this can be a benefit to performance, because the actual code is relatively short compared to the parameter preparation, the actual calling and the procedure prologue/epilogue.
If the procedure is too long, it can be a brake on performance though, and blow up your code gigantically. The "Auto" setting should make this decision for you, but in specific cases, you can locally set {$inline to on to force it. (e.g. for C macros translated to pascal functions, like the zlib functions to work with bitstreams )
Others have answered what inline does, but I just wanted to point out that there is a Compiler option to set inline on, off, or auto. Check out "Calling Procedures and Functions" in the D2009 docs for a very good explanation of the mechanics of inline. Here's the link to the online docs:
Delphi Online Docs for inline
It's borrowed from C in that it tells the compiler that this is a short routine that is frequently called and it recommends that the compiler treats the function as a macro and integrates the function code directly into the program at the point called rather than use a function call.
This gives faster code because there is no function call overhead, but at the expense of a larger program. Note too that like in C this is a recommendation to the compiler, it doesn't actually have to do so and the optimiser may override you.
Where to do this? Well like loop unwinding it's a technique that is very rarely of use nowadays. The classic place to use this is deep in a nested structure that is real-time critical, such as rendering code in a graphics application where a few machine calls shaved on each iteration can increase your screen refresh rate.
Press Ctrl + Alt + C (Entire CPU debug window) while debugging in Delphi, before call your inline function. And you will see that inline functions starts without "call" and wo jumping to another address. It's optimization feature.