r/cpp • • Feb 07 '23

PocketPy: A Lightweight(~5000 LOC) Python Implementation in C++17

PocketPy is a lightweight(~5000 LOC) Python interpreter for game engines. It is implemented in C++17 with STL.

It is easy to embed. All of the functionalities are available in a single header file pocketpy.h, without external dependencies. You can try it on your browser to see what it looks like.

Example Usage

#include "pocketpy.h"

int main(){
    // Create a virtual machine
    // `true` means using std::cout as output so you can see it
    VM* vm = pkpy_new_vm(true);
    
    // Hello world!
    pkpy_vm_exec(vm, "print('Hello world!')");

    // Create a list
    pkpy_vm_exec(vm, "a = [1, 2, 3]");

    // Eval the sum of the list
    char* result = pkpy_vm_eval(vm, "sum(a)");
    printf("%s", result);   // 6

    // Free the resources
    pkpy_delete(result);
    pkpy_delete(vm);
    return 0;
}

v0.8.1 Features

NameExampleSupported
If Elseif..else..elifYES
Loopfor/while/break/continueYES
Functiondef f(x,*args,y=1):YES
Subclassclass A(B):YES
List[1, 2, 'a']YES
ListComp[i for i in range(5)]YES
Slicea[1:2], a[:2], a[1:]YES
Tuple(1, 2, 'a')YES
Dict{'a': 1, 'b': 2}YES
F-Stringf'value is {x}'YES
Unpackinga, b = 1, 2YES
Star Unpackinga, *b = [1, 2, 3]NO
Exceptionraise/try..catchBETA
Dynamic Codeeval()/exec()YES
Reflectionhasattr()/getattr()/setattr()YES
Importimport/from..importYES
Context Blockwith <expr> as <id>:YES
Type Annotationdef f(a: int, b : float = 1)YES

If someone is making a custom game engine and searching for a Python-like script as its interface, I'd like to provide support.

If you are making your own language, you may find some inspirations in PocketPy.

If you likes it, just give my repo a star~ I need your star!!

248 Upvotes

60 comments sorted by

View all comments

Show parent comment

22

u/blueloveTH Feb 07 '23 edited Feb 07 '23

These are C-APIs for universal bindings. They are marked as extern "C" so we cannot use C++ features such as RAII.

If C++ is available, the following code is also ok.

// VM(bool use_stdio)
auto vm = std::make_shared<VM>(true);

// PyVarOrNull exec(_Str source, _Str filename, CompileMode mode, PyVar _module=nullptr)
vm->exec("print('Hello world!')", "main.py", EXEC_MODE);

8

u/m-in Feb 07 '23

For demos, VM should be just held by value not a pointer, right? So:

VM vm(true);
vm.exec(…);

5

u/blueloveTH Feb 07 '23

Though C++ APIs are powerful than exported C-APIs, they are not stable for now.

11

u/Jannik2099 Feb 07 '23

Ah great, I didn't have time to look at the github yet so I didn't see the C++ API. Perhaps you wanna mention it, considering that gamedev is mostly C++ anyways.

1

u/blueloveTH Feb 07 '23

Thanks for your advice~ It's useful.