C++ from Python
I was impressed today to see how easy it was to call a C++ DLL from Python. I got the following information from another site:
1. Create a file called dlltest.cpp and write a function that sums two numbers and returns the result:
//dlltest.cpp #define DLLEXPORT extern "C" __declspec(dllexport) DLLEXPORT int sum(int a, int b) { return a + b; }The extern "C" construct tells the compiler that the function is a C function. It also removes the decorations from the functions names in the DLL.
__declspec(dllexport) adds the export directive to the object file so you do not need to use a .def file.
2. Include the header of the function in dlltest.h://dlltest.h int sum(int, int);3. Create a new Dinamic-Link Library project and include the two files, compile, and create the DLL.
4. You can now use Dependency Walker to see the list of the exported functions. You should see here the sum function.
5. Move the DLL in the Python folder or use>>> import sys >>> sys.path.append(r"C:\path\of\dll")to include the DLL folder in the list of Python folders.
6. Use the ctypes module to access the DLL:
>>> from ctypes import * >>>mydll = cdll.dlltest >>> mydllNote: ctype module is already included from Python 2.5. If you are using an older version you can download ctypes here.
7. Now call the function:>>> sum = mydll.sum >>> sum <_FuncPtr object at 0x0097DBE8> >>> sum(5, 3) 8
Reposted from here... (Thanks!)
I need to get into Python more -- I've used Ruby a bit but have tended to ignore Python simply because I've not seen it is needed. Evidently, I need more side projects.
Google CTemplate
I just realized that I reinvented the wheel a month or so... I had a need for a nice templating language and although I did look for a solution that already existed, I didn't look hard enough. Google CTemplate is exactly what I wanted. My solution was basically to create this from scratch while ignoring all the complexities that I thought I wouldn't need. The result works (and may even be faster) but it feels clunky and it's not very flexible. You learn something new every day. Maybe with Rev2 of our release I'll start using this -- it certainly would be easier and the API is already documented.
From their website:
Here is a simple template file:
Hello {{NAME}},
You have just won ${{VALUE}}!
{{#IN_CA}}Well, ${{TAXED_VALUE}}, after taxes.{{/IN_CA}}Here is a C++ program to fill in the template, which we assume is stored in the file 'example.tpl':
#include <stdlib.h> #include <string> #include <iostream> #include <google/template.h> int main(int argc, char** argv) { google::TemplateDictionary dict("example"); dict.SetValue("NAME", "John Smith"); int winnings = rand() % 100000; dict.SetIntValue("VALUE", winnings); dict.SetFormattedValue("TAXED_VALUE", "%.2f", winnings * 0.83); // For now, assume everyone lives in CA. // (Try running the program with a 0 here instead!) if (1) { dict.ShowSection("IN_CA"); } google::Template* tpl = google::Template::GetTemplate("example.tpl", google::DO_NOT_STRIP); std::string output; tpl->Expand(&output, &dict); std::cout << output; return 0; }
Non-Conventional Advertising
To get in and out of town I must traverse about 2 miles of very built-up, very trafficky, retail- and service-dotted roadway. I was surprised to see over the last few years how often stores are using real, live humans as "flaggers" holding signs for their businesses or for special offers. Sure it's less creepy than dead people holding up signs, but my gut-instinct was that it would cost too much to pay someone and that the impact on sales would be minimal. Apparently my gut is wrong. According to this article I learned three things I'm surprised by:
- This is a competitive position
- People are fine with $7.50/hr for this work
- It can have a dramatic effect on sales
Don't get me wrong, money is money and I know that people will do all sorts of things. I just think it would be miserable work. Time would pass slowly as you stand in the cold with maybe a slight drizzle coming down. Cars beeping, bikes almost hitting you. Bleh... I'd much prefer the McDonald's job. On the bright side it takes no skill, you can probably listen to music and daydream.
On the other hand, I'm surprised that this really helps business. I can see how it may make some people aware of businesses that are squirreled away in strip malls. I guess I'm not part of the demographic who even uses strip-mall businesses for much of anything so perhaps I'm no more inclined to visit them whether they're having a special or not.
I don't know what my blog readers think, but I'm surprised. Any opinions? Any experience being influenced by or being a flagger?
Thanks to the Business Opportunities Weblog for the link...
So Pretty
It's truly amazing what beauty people can create. The Internet can be a fun place.
Wait for it to load and then move your cursor around and see what happens.
Because Perl is Too Straightforward…
...someone created Perligata.
Here's an example:
#! /usr/local/bin/perl -w use Lingua::Romana::Perligata; maximum inquementum tum biguttam egresso scribe. meo maximo vestibulo perlegamentum da. da duo tum maximum conscribementa meis listis. dum listis decapitamentum damentum nexto fac sic nextum tum novumversum scribe egresso. lista sic hoc recidementum nextum cis vannementa da listis. cis.
is equivalent to:
#! /usr/local/bin/perl -w print STDOUT 'maximum:'; my $maxim = <STDIN>; my (@list) = (2..$maxim); while ($next = shift @list) { print STDOUT $next, "\n"; @list = grep {$_ % $next} @list; }
No Way…
I think I actually got a snippet of Symbian code to work on the first attempt! This is a first... Maybe I'm actually getting the hang of this. I just find the whole "descriptor" concept very odd.
Anyway, all I was trying to do was replace all plus signs with spaces. I normally wrestle with descriptor nonsense for a while but this time, I got it on the first try!
_LIT(TestData, "THIS+IS+A+TEST"); HBufC* heapBuf = HBufC::NewLC(255); *heapBuf = TestData; TPtr pHeapBuf(heapBuf->Des()); while (heapBuf->Find(_L("+")) > 0) { pHeapBuf.Replace(heapBuf->Find(_L("+")), 1, _L(" ")); } CleanupStack::PopAndDestroy(heapBuf); //Don't forget!
Bleh... stupid Symbian. Thank goodness I didn't have to change the length of the descriptor...
Malaise
...not to be confused with mayonnaise (although both tend to ruin an otherwise tasty sandwich).
I've had a lot recently (again, malaise, not mayonnaise). There's a lot going on and I empathize with Alice:
"Well, in our country," said Alice, still panting a little, "you'd generally get to somewhere else — if you run very fast for a long time, as we've been doing."
"A slow sort of country!" said the Queen. "Now, here, you see, it takes all the running you can do, to keep in the same place. If you want to get somewhere else, you must run at least twice as fast as that!"
I'm way behind on reading, way behind on chores around the house (although I did finally wrap up my inspirational Plant Ledge Project). not keeping up with my supposedly rigorous exercise routine, behind on a huge bunch of personal geeky projects. Today I stayed home from work since I wasn't feeling so hot. I feel like I'm in continual deadlock as I analyze new tasks that I feel may be higher priority than my current tasks. There's no reason that I can't accomplish what I have in front of me, I just keep thinking that among the continual stream of tasks flowing at me, there might be a more critical task that I should immediately stick at the front of my queue. The problem is that except for very small tasks, almost all of my time is spent analyzing the incoming tasks. So even if I do identify the critical tasks and properly prioritize them, it doesn't really matter because unless a task can be done quickly, it will never actually have any opportunity to run despite its priority.
This causes feelings of guilt and malaise. Also, my cold doesn't help.
Updates
So I've been sloppy again and not updating the site.
Without further ado:
1) Safari Online was a little bit of a disappointment. I like the selection, the price is reasonable, the searchable formats are wonderful, the ability to cut and paste example code is stellar. So why disappointing? I don't use it. My reading is usually in the evening. I want to be able to sit back in the easy chair and read. My laptop is fairly comfortable but staring at a bright back-lit screen is most certainly not. It's just so much more comfortable to pick up a good old tree-based book and read that. Some of the advantages are still there. If I find something in my book, I can easily cut and paste it from Safari Online but now I'm basically just using Safari as a quick digital copy for all the books that I already have. Bleh... Not worth it. What would make it worth it? If the Kindle-gods worked with O'Reilly to make the entire Safari Online site browseable using your Kindle. I would buy it. I would pay extra. I would make a weekly pilgrimage to the Amazon headquarters. It would be great. But they don't. Furthermore, from what I've heard, on the software side, Kindle doesn't do tables, mono-space fonts, and some other things that really are almost required in order to read a technical programming/development related book.
2) Work has been busy. C/C++ has been pretty minimal... I'm getting much more comfortable with memory management issues and have been pleasantly surprised to see that most C++ code that I dig up out there basically looks like mine. I'm still definitely not an expert at decrypting some of the C++ deep magic code that I've seen, but then again, I bet the authors of most of that stuff don't even understand it anymore. C# has been a mixed bag. I've really enjoyed getting into the "new" features of 3.0 and 3.5 which I had been neglecting until recently. A lot of time spent on Stack Overflow has helped get m e up to speed with Linq and some of the other fun new language features. Generators, extension methods, anonymous functions... it's all sorts of fun.
3) I've been able to watch as the value of various investments that I can't easily cash out of has continued to dwindle. Thankfully, much of what I did have invested in long-term investments I was able to move to much less volatile funds but it's still been rough. On the bright side, the end of the world may be near as the Mayan calendar has it set to 2012. Obama would have the rare privilege of being the final President and (also on the bright side) wouldn't have to worry about his legacy as no one would care how big the national budget is at that point. Also, this would save me a lot of frustration with the whole Social Security thing. One can only hope...
4) Wife has been busy with her business. She's continued to embroider like crazy. I've been trying to push her to do more since she's only pregnant with 3 boys under 5 at home.
She tells me that some day she may expand her business but not now. I think she's in a good situation. On NPR (motto: Unbiased news since 1970 or whenever it was we started getting funded by liberals!) there was an interview with a business owner in the same general "baby products" market. Her remark was that the "economic crisis" we're experiencing will likely drive a baby boom as people's lives and schedules slow down and more time is spent at home. But hopefully the economy picks up soon so they can afford overpriced baby products for their new brood. I got her a new iPhone so that she can become more of a geek. She really isn't nearly geeky enough and it bothers me. I was interested to see that even the Taliban are getting in on the iPhone action (see picture).
Time precludes further updates.
...Will write more later...