slycelote's blog

By slycelote, history, 9 years ago, In English

I'm sure most of you know that all mainstream C++ compilers support inline assembly language. But did you know that you can actually embed Python in a similar way?

Here, for instance, I implemented gcd function in Python simply because it's easier and shorter. The rest of the code is in C++: 17084249. (By the way, kudos to Codeforces for correct highlighting of both Python and C++ parts!)

I'm not sure if it can be useful at all, but I thought that it's fun to share. Keep in mind it doesn't work in all compilers though!

  • Vote: I like it
  • +530
  • Vote: I do not like it

»
9 years ago, # |
  Vote: I like it -59 Vote: I do not like it

Lol very nice, only figured it out when tried pasting code in and saw the large amount of whitespace. Goes to show how little I know about c++ that I actually thought this was possible.

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Which compiler do you use?

»
9 years ago, # |
  Vote: I like it +141 Vote: I do not like it

There are many blogs to teach a topic or a technique. And none of them is close to this one in terms of usefulness. Sir, you amazed me.

»
9 years ago, # |
  Vote: I like it +13 Vote: I do not like it

This is amazing, but how does c++ interpretate python objects?

What happens if you try to return python list or dictionary?

Can't check it on my own cause I don't have monitor atm :(

»
9 years ago, # |
Rev. 2   Vote: I like it +69 Vote: I do not like it

Cool post! BTW, this code with slight changes works in another compiler. 17088203

»
9 years ago, # |
  Vote: I like it -10 Vote: I do not like it

+1, Interesting. ;)

»
9 years ago, # |
  Vote: I like it -54 Vote: I do not like it

I wouldn't say that it's easier or shorter when we consider the template around the function itself, but I can see it having great application elsewhere — for example in bignum problems with not too tight time limits.

»
9 years ago, # |
  Vote: I like it -102 Vote: I do not like it

slycelote is trolling us. Just open his code in submissions list and scroll to the right)))

»
9 years ago, # |
  Vote: I like it +39 Vote: I do not like it

2 april mode on: It's possible

#include <iostream>
#include <string>
#define BOOST_PYTHON_STATIC_LIB
#pragma comment (lib, "python27.lib")
#include <boost/python.hpp>

using namespace std;
using namespace boost::python;

int main()
{
    Py_Initialize();
    try {
        object main_ns = import("__main__").attr("__dict__");
        cout << extract<char *>(eval("str(2 ** 1000)", main_ns));
    } catch (const error_already_set&) {
        PyErr_Print();
    }
}
»
9 years ago, # |
  Vote: I like it +35 Vote: I do not like it

Best April Fools Ever.

»
9 years ago, # |
  Vote: I like it +16 Vote: I do not like it

Luckily, I view the code on my cell-phone.