Python C API接口函数

//============================================================================
// Name        : MyTest.cpp
// Author      : Arts
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include 
#include "Python.h"
#include "stdlib.h"
using namespace std;

void very_high_layer() {
	wchar_t *program = Py_DecodeLocale("MyProgram", NULL);
	if (program == NULL) {
		fprintf(stderr, "Fatal error: cannot decode MyProgram\n");
		exit(1);
	}
	Py_SetProgramName(program); /* optional but recommended */
	Py_Initialize();
	PyRun_SimpleString("from time import time,ctime\n"
			"print('Today is', ctime(time()))\n");
	if (Py_FinalizeEx() < 0) {
		exit(120);
	}
	PyMem_RawFree(program);
	return;
}

int run_func() {
	PyObject *pName, *pModule, *pFunc;
	PyObject *pArgs, *pValue;
	int i;

	Py_Initialize();

	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append(\"/root/PycharmProjects/untitled\")");

	pName = PyUnicode_DecodeFSDefault("hello");
	/* Error checking of pName left out */

	pModule = PyImport_Import(pName);
	Py_DECREF(pName);

	if (pModule != NULL) {
		pFunc = PyObject_GetAttrString(pModule, "my_add");
		/* pFunc is a new reference */

		if (pFunc && PyCallable_Check(pFunc)) {
			pArgs = PyTuple_New(2);
			const char* argv[] = { "4", "5" };
			for (i = 0; i < 2; ++i) {
				pValue = PyLong_FromLong(atoi(argv[i]));
				if (!pValue) {
					Py_DECREF(pArgs);
					Py_DECREF(pModule);
					fprintf(stderr, "Cannot convert argument\n");
					return 1;
				}
				/* pValue reference stolen here: */
				PyTuple_SetItem(pArgs, i, pValue);
			}
			pValue = PyObject_CallObject(pFunc, pArgs);
			Py_DECREF(pArgs);
			if (pValue != NULL) {
				printf("Result of call: %ld\n", PyLong_AsLong(pValue));
				Py_DECREF(pValue);
			} else {
				Py_DECREF(pFunc);
				Py_DECREF(pModule);
				PyErr_Print();
				fprintf(stderr, "Call failed\n");
				return 1;
			}
		} else {
			if (PyErr_Occurred())
				PyErr_Print();
			fprintf(stderr, "Cannot find function \"%s\"\n", "my_add");
		}
		Py_XDECREF(pFunc);
		Py_DECREF(pModule);
	} else {
		PyErr_Print();
		fprintf(stderr, "Failed to load \"%s\"\n", "hello");
		return 1;
	}
	if (Py_FinalizeEx() < 0) {
		return 120;
	}
	return 0;
}

int Run_Utilities(int num, ...) {
	PyObject *pValue, *presult, *pmodule, *pret;

	Py_Initialize();
	PyRun_SimpleString("import threading");

	wchar_t* pstr;
	const char* mystring = "奔跑吧兄弟!";
	size_t mystrlen = sizeof(mystring);
	size_t* pmystrlen = &mystrlen;
	// 1 byte char --> 4 bytes wchar_t
	pstr = Py_DecodeLocale(mystring, pmystrlen);
	printf("Py_DecodeLocale: %ls\n", pstr);
	char* myencodestr;
	size_t errpos = sizeof(int);
	size_t* perrpos = &errpos;
	// 4 bytes wchar_t --> 1 byte char
	myencodestr = Py_EncodeLocale(pstr, perrpos);
	printf("Py_EncodeLocale: %s\n", myencodestr);

	// get objects in sys. in this example, get sys.path
	pValue = PySys_GetObject("path");
	cout << "PySys_GetObject: ";
	PyObject_Print(pValue, stdout, 0);
	cout << endl;

	// Import Module
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append(\"/root/PycharmProjects/untitled\")");
	pmodule = PyImport_ImportModule("hello");
	cout << "PyImport_ImportModule: ";
	PyObject_Print(pmodule, stdout, 0);
	cout << endl;
	Py_DECREF(pmodule);

	// get dict in sys.modules
	presult = PyImport_GetModuleDict();
	cout << "PyImport_GetModuleDict: ";
	PyObject_Print(presult, stdout, 0);
	cout << endl;

	// build value
	pValue = Py_BuildValue("i", 123);
	cout << "Py_BuildValue: ";
	PyObject_Print(pValue, stdout, 0);
	cout << endl;
	// parse value
	int ivalue;
	PyArg_Parse(pValue, "i", &ivalue);
	cout << "PyArg_Parse: " << ivalue << endl;
	Py_XDECREF(pValue);

	// build serveral values
	va_list va;
	va_start(va, num);
	pValue = Py_VaBuildValue("(i, i, i)", va);
	cout << "Py_VaBuildValue: ";
	PyObject_Print(pValue, stdout, 0);
	cout << endl;
	// parse tuple
	int i = 0, j = 0, k = 0;
	PyArg_ParseTuple(pValue, "iii", &i, &j, &k);
	cout << "i:" << i << endl << "j:" << j << endl << "k:" << k << endl;
	va_end(va);
	Py_XDECREF(pValue);

	// 获取当前所在函数的内建量
	presult = PyEval_GetBuiltins();
	cout << "PyEval_GetBuiltins: ";
	PyObject_Print(presult, stdout, 0);
	cout << endl;

	// codec: encode and decode
	pValue = Py_BuildValue("s", "Hello World!");
	presult = PyCodec_Encode(pValue, "utf-16-le", "strict");
	PyObject_Print(presult, stdout, 0);
	cout << endl;
	pret = PyCodec_Decode(presult, "utf-16-le", "strict");
	PyObject_Print(pret, stdout, 0);
	cout << endl;

	if (Py_FinalizeEx() < 0) {
		return 120;
	}
	return 0;
}

int main(int argc, char *argv[]) {
	int ret = 0;

#if 0 // 直接在C编译器中运行python语句
	very_high_layer();
#elif 0 // 执行.py脚本中的函数
	ret = run_func();
#elif 1 // 测试常用函数
	ret = Run_Utilities(3, 111, 222, 333);
#endif

	return ret;
}

你可能感兴趣的:(Python C API接口函数)