C + + Call Python series (1): struct as entry and return structure

Source: Internet
Author: User
Tags pack unpack

Recently you are planning to use python as a test case for functional testing and stress testing of game servers;

Because the server is written in C + +, the TCP protocol, the current architecture is intended to use the python constructs the structure, transmits to the C + + layer to send the socket to the game server, the response message is then referred to Python for verification;

Begin:

The first is the C + + call Python layer needs to get through;

Fortunately, Python has its own set of libraries that provide C/s for calls;

Below I put the code, with the Vs2013,python 2.7

1 //python_c++.cpp: Defines the entry point of the console application. 2 //3 4#include"stdafx.h"5#include <Python.h>6 #pragmaComment (lib, "Ws2_32.lib")7 8 int_tmain (intARGC, _tchar*argv[])9 {Ten     //Initialize Python One py_initialize (); A     //Check if initialization is successful -     if(!py_isinitialized ()) { -         return-1; the     } -     //Add current Path -     //runs the input string directly as Python code, returning 0 -     //indicates success, 1 indicates an error. Most of the time the error is due to a syntax error in the string.  +Pyrun_simplestring ("Import SYS"); -     intresult = Pyrun_simplestring ("print ('----------import sys-------')"); +     if(result!=-1){ Aprintf"Test Pyhon ok!\n\n"); at     } -      -Pyrun_simplestring ("sys.path.append ('./')"); -  -     //load a script named Pytest -Pyobject *pname = pybytes_fromstring ("pytest"); inPyobject *pmodule =Pyimport_import (pName); -     if(!pmodule) { toprintf"can ' t find pytest.py"); + GetChar (); -         return-1; the     } *  $Pyobject *pdict =pymodule_getdict (pmodule);Panax Notoginseng     if(!pdict) { - GetChar (); the         return-1; +     } A  the     //The following is a find function test and execute test +Pyobject *pfunc = pydict_getitemstring (Pdict,"test2"); -     if(!pfunc | |!Pycallable_check (PFunc)) { $printf"can ' t find function [Test2]"); $ GetChar (); -         return-1; -     } the  -typedefstructHeader_ {Wuyi         intbuf1; the         intbuf2; -         Charbuf3[ One]; Wu         intBuf4; - }header; About  $     //Create a struct body - header input; -memset (&input,0,sizeof(input)); -INPUT.BUF1 =1; AINPUT.BUF2 =2; +INPUT.BUF4 =3; thestrcpy_s (INPUT.BUF3,"Kjac"); -      $     //packaged into byte* the     Char* Byinput =New Char(sizeof(input)); thememcpy (Byinput, &input,sizeof(input)); the  the     //Request a Python entry -Pyobject *pargs = Pytuple_new (1); in     //assigns a value to the Python entry; s represents the char* format, #代表传入指定长度 thePytuple_setitem (PArgs,0, Py_buildvalue ("s#", Byinput,sizeof(input))); the  About     //Execute function thePyobject *presult =Pyobject_callobject (PFunc, PArgs); the  the     Char*pRsp; +     //Get return value -Pyarg_parse (PResult,"s", &pRsp); the Bayi     //turn into a structural body theheader* PSTRSP = (header*) pRsp; theprintf"\ n-----------C + + layer receives a PY return: buf1:%d,buf2:%d,buf3:%s,buf4:%d\n",  -PSTRSP-&GT;BUF1, Pstrsp->buf2, PSTRSP-&GT;BUF3, pstrsp->buf4); -  the     //Release the Py_decref (pName); the Py_decref (PArgs); the Py_decref (pmodule); -  the     //Close Python the py_finalize (); the GetChar ();94     return 0; the}

The following is the Python code

1 Importstruct2 3 defTest (a):4     Print("----------------------------python 1-----------------------")5ret = Struct.unpack ('Ii11si', a)6     Print("----------------------------python deal-----------------------")7     Print("--------------------Python receive C + + struct:")8     Print("Begin Unpack:")9     Print("")Ten     Print(ret) OneBUF1 = ret[0] + 1 ABUF2 = ret[1] + 1 -BUF4 = ret[3] + 1 -     Print("--------------------begin pack data and begin send to C + +") the     Print("") -Bin_buf_all = Struct.pack ('Ii11si', Buf1, Buf2,"DFDS", BUF4) -     Print("----------------------------python End-----------------------") -     returnBin_buf_all

The following is attached to VS2013 's Engineering property modification

Set include and libs paths for Python projects

Next, you can compile the output;

----------Import sys-------Test pyhon OK!----------------------------python 1------------------------------------- --------------python deal-------------------------------------------python receive C + + Struct:begin Unpack: (1, 2, ' Kjac\x00\xfe\xfe\xfe\xfe\xfe\xfe ', 3)--------------------begin pack data and begin send to C + +------------------------ ----Python End----------------------------------C + + layer receives a PY return: Buf1:2,buf2:3,buf3:dfds,buf4:4

Now that C + + calls Python is done, here is the framework message between Python and C + + and the construction of the test code

C + + Call Python series (1): struct as entry and return structure

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.