vcpkg install python3
cmake_minimum_required(VERSION 3.0.0)
project(c++_python VERSION 0.1.0 LANGUAGES C CXX)
# python
find_package(Python3 COMPONENTS Development REQUIRED)
add_executable(c++_python main.cpp)
# libs
target_link_libraries(${PROJECT_NAME} PRIVATE Python3::Python)
#include
int main(int, char**){
Py_Initialize();
PyRun_SimpleString("print('hello')");
Py_Finalize();
return 0;
}
#include
#include
#include
#include
int main(int, char**){
std::string filename="../test.py";
std::wstring wfilename=std::wstring(filename.begin(),filename.end());
std::wstring mode=L"r";
FILE* file;
Py_Initialize();
file=_Py_wfopen(wfilename.c_str(),mode.c_str());
// PyRun_SimpleString("print('hello')");
PyRun_SimpleFile(file,filename.c_str());
Py_Finalize();
return 0;
}
#ifndef PYHELPER_HPP
#define PYHELPER_HPP
#pragma once
#include
class CPyInstance
{
public:
CPyInstance()
{
Py_Initialize();
}
~CPyInstance()
{
Py_Finalize();
}
};
class CPyObject
{
private:
PyObject *p;
public:
CPyObject() : p(NULL)
{}
CPyObject(PyObject* _p) : p(_p)
{}
~CPyObject()
{
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 ? true : false;
}
operator PyObject*()
{
return p;
}
PyObject* operator = (PyObject* pp)
{
p = pp;
return p;
}
operator bool()
{
return p ? true : false;
}
};
#endif
then call function:
CPyInstance hInstance;
//import module
CPyObject pName = PyUnicode_FromString("pyemb3");
CPyObject pModule = PyImport_Import(pName);
if(pModule)
{
CPyObject pFunc = PyObject_GetAttrString(pModule, "getInteger");
if(pFunc && PyCallable_Check(pFunc))
{
//call func
CPyObject pValue = PyObject_CallObject(pFunc, NULL);
printf_s("C: getInteger() = %ld\n", PyLong_AsLong(pValue));
}
else
{
printf("ERROR: function getInteger()\n");
}
}
else
{
printf_s("ERROR: Module not imported\n");
}