1

I have a cryptography project I am working on, and the module I am using is Python only so I can't use it in C++. I would like to compile the Python code into a .pyc file (a compiled python file) and use this in my C++ project.

I would like to call these functions in my C++ code as I please and have it execute smoothly. How can I go about doing this? If the method I am desiring isn't feasible, how can I achieve this with an alternate method?

Desired result: I use the .pyc file and its functions seamlessly in my C++ code. If my question sucks, please tell me why!

Reproducible Python Code (It will compile the python code for you when it runs.)

import hashlib
import py_compile

py_compile.compile("crypto.py")

def generate_keys():
    public_key = "Please help me".encode("utf-8")
    alphanumeric_address = hashlib.sha256(public_key).hexdigest()
    return public_key, alphanumeric_address

Sample C++ Code:

#include <iostream>
// Do whatever you need to import the function in here.

int main ()
{

    std::string alphanumeric_address = /* Import Python Function here as a variable, calling the
        alphanumeric_address specified in the generate_keys() function */

    std::cout << alphanumeric_address << std::endl;

}
  • 1
    `.pyc` files are merely "byte-compiled" Python code and still need the Python interpreter to execute them. You could run them as a separate process by passing them to the python executable on your machine and communicate with them via stdin, stdout, and command-line arguments like any other separate process. It's also possible to embed the python interpreter in your compiled C++ program and call it programmatically — which sounds more like what you want and will need to do to call individual function like that. – martineau Jun 10 '22 at 21:04
  • See [Embedding the CPython runtime in a larger application](https://docs.python.org/3/extending/index.html#embedding-the-cpython-runtime-in-a-larger-application) – martineau Jun 10 '22 at 21:07
  • How does embedding the Python interpreter in the C++ code affect performance, will it affect performance? –  Jun 11 '22 at 00:37
  • Yes it will affect performance, but I have no idea how much or compared to what — there is some overhead involved of course in initializing the embedded interpreter. Premature optimization is the root of all evil. – martineau Jun 11 '22 at 00:44
  • Well, how do you think I can embed a regular Python file in the same code, same advice? –  Jun 11 '22 at 00:49
  • There is no way to embed and run Python code in a C++ executable except by also embedding the Python runtime in it, too. – martineau Jun 11 '22 at 00:58
  • Do you know how to get the file? –  Jun 11 '22 at 01:59
  • You can download the Python source files from [python.org/downloads/source](https://www.python.org/downloads/source). It's in the `Include` directory. – martineau Jun 11 '22 at 08:08

0 Answers0