在架构服务器的时候,使用了IOCP来收发数据,使用Python写解包入库程序,那么要让两个进程通信,有很多方法,这里使用了内存共享的方法
python本来没有内存共享(我没有找到,也不知道是不是真的没有,但是和C++的程序共享内存,我想确实没有的吧),那么只好自己用C写个扩展,方法记录下来,以备后用
 
首先是扩展的*.c程序
MEM.c
InBlock.gif#include "Python.h"
InBlock.gif#include <windows.h>
InBlock.gif#include <stdio.h>
InBlock.gif
InBlock.gif int ShareMemory( char arg[], char str[]){
InBlock.gif  HANDLE hMapFile = OpenFileMapping(
InBlock.gif      FILE_MAP_ALL_ACCESS,
InBlock.gif      FALSE,
InBlock.gif      arg
InBlock.gif      );
InBlock.gif   if(hMapFile == NULL){
InBlock.gif     return 1;
InBlock.gif  }
InBlock.gif  LPVOID lpMapAddress = MapViewOfFile(
InBlock.gif      hMapFile,
InBlock.gif      FILE_MAP_ALL_ACCESS,
InBlock.gif      0,
InBlock.gif      0,
InBlock.gif      0
InBlock.gif      );
InBlock.gif   if(lpMapAddress == NULL){
InBlock.gif     return 1;
InBlock.gif  }
InBlock.gif
InBlock.gif //  cout << (char *)lpMapAddress << endl;
InBlock.gif  lstrcpy(str,( char *)lpMapAddress);
InBlock.gif  UnmapViewOfFile(lpMapAddress);
InBlock.gif   return 0;
InBlock.gif}
InBlock.gif
InBlock.gif static PyObject *
InBlock.gifPyExt_fac(PyObject *self,PyObject *args){
InBlock.gif   char *str;
InBlock.gif   char str1[4096];
InBlock.gif  PyObject *retval;
InBlock.gif   if(!PyArg_ParseTuple(args, "s",&str));
InBlock.gif  ShareMemory(str,str1);
InBlock.gif  retval = (PyObject *)Py_BuildValue( "s",str1);
InBlock.gif   return retval;
InBlock.gif}
InBlock.gif
InBlock.gif static PyMethodDef
InBlock.gifPyExtMethods[] = {
InBlock.gif  { "fac",PyExt_fac,METH_VARARGS},
InBlock.gif  {NULL,NULL}
InBlock.gif};
InBlock.gif
InBlock.gif void initPyExt(){
InBlock.gif  Py_InitModule( "PyExt",PyExtMethods);
InBlock.gif}
 
接下来写setup.py编译
from distutils.core import setup,Extension

MOD = 'PyExt'

setup(name=MOD,ext_modules=[
        Extension(MOD,sources=['MEM.c'])])
 
在命令行下键入:
setup.py build -c mingw32
如果安装了vs2003那么只要这样
setup.py build
如果看到这样的提示:
running build
running build_ext
building 'PyExt' extension
D:\Qt\QtCreator\mingw\bin\gcc.exe -mno-cygwin -mdll -O -Wall -ID:\Python25\include -ID:\Python25\PC
-c MEM.c -o build\temp.win32-2.5\Release\mem.o
writing build\temp.win32-2.5\Release\PyExt.def
D:\Qt\QtCreator\mingw\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.5\Release\mem.o build\te
mp.win32-2.5\Release\PyExt.def -LD:\Python25\libs -LD:\Python25\PCBuild -lpython25 -lmsvcr71 -o buil
d\lib.win32-2.5\PyExt.pyd
说明编译成功了,编译后的.pyc文件在build\lib.win32-2.5目录里
吧这个.pyc文件拷贝到工程目录下,建立一个py文件来测试一下
from PyExt import fac
str2 = fac('你的共享内存申请字符串')
print str2
运行这个程序:
已经获得了正确的输出