#include <stdio.h> #include <Python.h> #include <iostream> using namespace std; #pragma comment(lib, "python34.lib") void HelloWorld(); void Add(); void TestTransferdict(); void TestClass(); static PyObject * __Test_Hello(PyObject *self, PyObject *args) { printf("Hello, world++++++\n" ); Py_INCREF(Py_None); return Py_None; } static PyMethodDef GameMethods[] = { {"Test_Hello", __Test_Hello, METH_NOARGS, NULL}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef GameModule = { PyModuleDef_HEAD_INIT, "Game", NULL, 0, GameMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_Game(void) { PyObject *module; module = PyModule_Create(&GameModule); if (module == NULL) return NULL; return module; } int main() { /* char buf[4] = {0}; int &pi = *((int*)buf); buf[0] = 1; buf[1] = 2; buf[2] = 3; buf[3] = 4; int i1 = unsigned char(pi); int i2 = unsigned char(pi >> 8); int i3 = unsigned char(pi >> 16); int i4 = unsigned char(pi >> 24); */ /* cout<<"start test..."<<endl; cout<<"hello world();"<<endl; HelloWorld(); cout<<"add();"<<endl; Add(); cout<<"test_dist();"<<endl; TestTransferdict();*/ PyImport_AppendInittab("Game", PyInit_Game); HelloWorld(); system("pause"); return 0; } void HelloWorld() { Py_Initialize(); PyObject* pMoudle = NULL; PyObject* pFunc = NULL; pMoudle = PyImport_ImportModule("Test001"); pFunc = PyObject_GetAttrString(pMoudle,"HelloWorld"); PyEval_CallObject(pFunc,NULL); Py_Finalize(); } void Add() { Py_Initialize(); PyObject* pMoudle = NULL; PyObject* pFunc = NULL; pMoudle = PyImport_ImportModule("Test001"); pFunc = PyObject_GetAttrString(pMoudle,"add"); PyObject* pArgs = PyTuple_New(2); PyTuple_SetItem(pArgs,0,Py_BuildValue("i",5)); PyTuple_SetItem(pArgs,1,Py_BuildValue("i",7)); PyObject* pReturn = NULL; pReturn = PyEval_CallObject(pFunc,pArgs); int result; PyArg_Parse(pReturn,"i",&result); cout<<"5+7 = "<<result<<endl; Py_Finalize(); } void TestTransferdict() { Py_Initialize(); PyObject* pMoudle = NULL; PyObject* pFunc = NULL; pMoudle = PyImport_ImportModule("Test001"); pFunc = PyObject_GetAttrString(pMoudle,"TestDict"); PyObject* pArgs = PyTuple_New(1); PyObject* pDict = PyDict_New(); PyDict_SetItemString(pDict,"Name",Py_BuildValue("s","WangYao")); PyDict_SetItemString(pDict,"Age",Py_BuildValue("i",25)); PyTuple_SetItem(pArgs,0,pDict); PyObject* pReturn = NULL; pReturn = PyEval_CallObject(pFunc,pArgs); int size = PyDict_Size(pReturn); cout<<"返回字典的大小爲:"<<size<<endl; PyObject* pNewAge = PyDict_GetItemString(pReturn,"Age"); int newAge; PyArg_Parse(pNewAge,"i",&newAge); cout<<"True age:"<<newAge<<endl; Py_Finalize(); } void TestClass() { /* Py_Initialize(); PyObject* pMoudle = NULL; PyObject* pFunc = NULL; pMoudle = PyImport_ImportModule("Test001"); pFunc = PyObject_GetAttrString(pMoudle,"TestDict"); PyObject* pClassPerson = PyObject_GetAttrString(pMoudle,"Person"); PyObject* pInstancePerson = PyInstance_New(pClassPerson,NULL,NULL); //python3.4.2 不支持該api PyObject_CallMethod(pInstancePerson,"greet","s","hello kitty"); Py_Finalize(); */ }