Skip to content

Instantly share code, notes, and snippets.

@vlzx
Last active January 19, 2024 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlzx/bd70f5810bfcbd3f4f33a3a1c4cb22d2 to your computer and use it in GitHub Desktop.
Save vlzx/bd70f5810bfcbd3f4f33a3a1c4cb22d2 to your computer and use it in GitHub Desktop.
Call Python code from C++
#include <iostream>
#include <pybind11/embed.h> // everything needed for embedding
#include <pybind11/numpy.h>
namespace py = pybind11;
py::array_t<double> create2DArray(int rows, int cols) {
py::array_t<double> result({rows, cols});
auto ptr = result.mutable_data();
/*
ptr[0] | ptr[1] | ptr[2]
ptr[3] | ptr[4] | ptr[5]
*/
ptr[0] = 1.0;
ptr[1] = 2.0;
ptr[2] = 3.0;
ptr[3] = 4.0;
ptr[4] = 5.0;
ptr[5] = 6.0;
return result;
}
int main() {
py::scoped_interpreter guard{}; // start the interpreter and keep it alive
try
{
py::print("Hello, World!"); // use the Python API
py::module_ calc = py::module_::import("calc");
py::array_t<double> arrayA = create2DArray(2, 3);
py::array_t<double> arrayB = create2DArray(2, 3);
py::dict res = calc.attr("add_np")(arrayA, arrayB);
auto array = res["result"].cast<py::array_t<double>>();
auto answer = res["answer"].cast<int>();
std::cout << "Answer: " << answer << std::endl;
for (size_t i = 0; i < 6; i++)
{
std::cout << array.mutable_data()[i] << std::endl;
}
}
catch(const py::error_already_set& e) {
PyErr_Print();
std::cerr << "Python Error: " << e.what() << std::endl;
}
catch(const std::exception& e)
{
std::cerr << "C++ Exception: " << e.what() << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment