Last active
July 21, 2021 19:46
-
-
Save polymorphm/7206252 to your computer and use it in GitHub Desktop.
test (hello world) python-c-api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// -*- mode: cpp; coding: utf-8 -*- | |
// | |
// $ g++ -pedantic -std=c++11 -o test-py test-py.cpp $(pkg-config --cflags --libs python3) | |
// | |
#include <clocale> | |
#include <cstdlib> | |
#include <Python.h> | |
int main(int argc, char *argv[]) { | |
setlocale(LC_ALL, ""); | |
size_t main_path_size = 100000; | |
wchar_t *main_path = 0; | |
main_path = new wchar_t[main_path_size]; | |
mbstowcs(main_path, argv[0], main_path_size - 1); | |
main_path[main_path_size - 1] = 0; | |
Py_Initialize(); | |
PySys_SetArgv(1, &main_path); | |
PyObject *vars = Py_BuildValue( | |
"{s:s,s:s,s:s}", | |
"var_a", | |
"VAR_A_VAL", | |
"var_b", | |
"VAR_Bфиг няBB_VAL", | |
"var_for_mod", | |
"проверка модуля" | |
); | |
PyDict_SetItemString(vars, "__builtins__", PyEval_GetBuiltins()); | |
PyObject *result = 0; | |
result = PyRun_String( | |
"x = 123 + 4\n", | |
Py_file_input, | |
vars, | |
0 | |
); | |
if (!result) { | |
wprintf(L"error 1!\n"); | |
} | |
Py_CLEAR(result); | |
result = PyRun_String( | |
"print(x)\n" | |
"print('var_a is {!r}; var_b is {!r}'.format(var_a, var_b))\n" | |
"import sys\n" | |
"print(sys.path)\n", | |
Py_file_input, | |
vars, | |
0 | |
); | |
if (!result) { | |
wprintf(L"error 2!\n"); | |
} | |
Py_CLEAR(result); | |
result = PyRun_String( | |
"import test_mod\n" | |
"test_mod.test_func(var_for_mod)\n", | |
Py_file_input, | |
vars, | |
0 | |
); | |
if (!result) { | |
wprintf(L"error 3!\n"); | |
} | |
Py_CLEAR(result); | |
Py_CLEAR(vars); | |
Py_Finalize(); | |
if (main_path) { | |
delete[] main_path; | |
main_path = 0; | |
} | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CONFIG += console | |
SOURCES += test-py.cpp | |
win32 { | |
INCLUDEPATH += C:/devel/Python33/include | |
LIBS += C:/devel/Python33/libs/python33.lib | |
} | |
unix { | |
CONFIG += link_pkgconfig | |
PKGCONFIG += python3 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- mode: python; coding: utf-8 -*- | |
def test_func(v): | |
print('*** good module! {!r} ***'.format(v)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment