Skip to content

Instantly share code, notes, and snippets.

@alyoshenka
Created April 2, 2020 19:15
Show Gist options
  • Save alyoshenka/45ac4cbf1cafc77456c3b2361098b665 to your computer and use it in GitHub Desktop.
Save alyoshenka/45ac4cbf1cafc77456c3b2361098b665 to your computer and use it in GitHub Desktop.
Call Python from C++
#include <stdio.h>
#include <conio.h>
#include "pyhelper.hpp"
// https://www.codeproject.com/Articles/820116/Embedding-Python-program-in-a-C-Cplusplus-code
int main()
{
CppPyInstance pyInstance;
CppPyObject pName = PyUnicode_FromString("nut");
CppPyObject pModule = PyImport_Import(pName);
if (pModule)
{
CppPyObject pFunc = PyObject_GetAttrString(pModule, "printNut");
if (pFunc && PyCallable_Check(pFunc))
{
CppPyObject pValue = PyObject_CallObject(pFunc, NULL);
printf_s("Cpp: %ld\n", PyLong_AsLong(pValue));
}
else { printf("Error func: %d check: %d", pFunc, PyCallable_Check(pFunc)); }
}
else { printf("Error: module"); }
return 0;
}
def printNut():
print("Nut")
return 5
/*
this code taken from https://www.codeproject.com/Articles/820116/Embedding-Python-program-in-a-C-Cplusplus-code
it is totally 100% copied and in no way mine
*/
#ifndef PYHELPER_HPP
#define PYHELPER_HPP
#pragma once
#include <Python.h>
class CppPyInstance
{
public:
CppPyInstance() { Py_Initialize(); }
~CppPyInstance() { Py_Finalize(); }
};
class CppPyObject
{
private:
PyObject* p;
public:
CppPyObject() : p(NULL) {}
CppPyObject(PyObject* _p) : p(_p) {}
~CppPyObject() { Release(); }
PyObject* getObject() { return p; }
PyObject* setObject(PyObject* _p) { return (p = _p); }
PyObject* AddRef()
{
if (p) { Py_INCREF(p); }
return p;
}
void Release()
{
if (p) { Py_DECREF(p); }
p = NULL;
}
PyObject* operator ->() { return p; }
bool is() { return p; }
operator PyObject* () { return p; }
PyObject* operator = (PyObject* pp)
{
p = pp;
return p;
}
operator bool() { return p; }
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment