Chinaunix首页 | 论坛 | 博客
  • 博客访问: 658055
  • 博文数量: 102
  • 博客积分: 2241
  • 博客等级: 大尉
  • 技术积分: 1670
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-08 10:08
文章分类

全部博文(102)

文章存档

2013年(6)

2012年(15)

2011年(81)

分类: Python/Ruby

2011-06-20 23:49:52


db2 win samples 代码使用cl编译,要使用gcc编译,cl参数转换成gcc参数


c调用python函数的包装程序    c执行python代码,取python返回值

/**
 * convert msvc cl param to gcc param
 * 2010 2011 windwiny
 */

#include
#include
#include
#include
#include

#define MAXX 10240

void SetColor(unsigned short ForeColor, unsigned short BackGroundColor) {
    HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hCon, ForeColor | BackGroundColor);
}

void color(char *cl, char *msg) {
    int x;
    if (strcasecmp(cl, "r") == 0 || strcasecmp(cl, "red") == 0)
        x = 0xC;
    else if (strcasecmp(cl, "g") == 0 || strcasecmp(cl, "green") == 0)
        x = 0xA;
    else if (strcasecmp(cl, "b") == 0 || strcasecmp(cl, "blue") == 0)
        x = 0x9;
    else
        x = atoi(cl);
    if (x != 0)
        SetColor(x, 0x0);
    printf("%s\n", msg);
    SetColor(0x7, 0x0);
}

void colori(char *cl, int rc) {
    int x;
    if (strcasecmp(cl, "r") == 0 || strcasecmp(cl, "red") == 0)
        x = 0xC;
    else if (strcasecmp(cl, "g") == 0 || strcasecmp(cl, "green") == 0)
        x = 0xA;
    else if (strcasecmp(cl, "b") == 0 || strcasecmp(cl, "blue") == 0)
        x = 0x9;
    else
        x = atoi(cl);
    if (x != 0)
        SetColor(x, 0x0);
    printf("%d", rc);
    SetColor(0x7, 0x0);
}

int main(int argc, char* argv[]) {
    int DEBUG = 0;
    int i = 0;
    int rc = 0;
    char szCmd[MAXX];
    char szName[256];

    if (argc > 1 && strcmp("-d", argv[1]) == 0)
        DEBUG = 1;

    do {
        char szPath[MAXX];
        memset(szPath, '\0', MAXX);
        memset(szName, '\0', 256);
        memset(szCmd, '\0', MAXX);
        GetModuleFileName(NULL, szPath, MAXX);
        if (DEBUG)
            printf(" * DEBUG: ModuleFileName : %s\n", szPath);
        char* p = strrchr(szPath, '\\');
        if (p == NULL) {
            printf("Get module file name error!\n");
            return -1;
        }
        strncpy(szName, p + 1, strlen(p) - 5);
        if (DEBUG)
            printf(" * DEBUG: pgName: %s\n", szName);
        *p = 0;

        sprintf(
                szCmd,
                ""
                "import sys\n"
                "sys.path = ['.', r'%s\\mysrc.zip', r'%s\\stdlib.zip', r'%s\\dlls'] + sys.path\n"
                "if not hasattr(sys, 'argv'):\n"
                "    sys.argv = []\n"
                "", szPath, szPath, szPath);
    } while (0);

    // Py_OptimizeFlag = 2;
    Py_NoSiteFlag = 1;
    Py_Initialize();

    do {
        char *cstr = NULL;
        PyObject *ret = NULL, *dict = NULL, *pytmp1;
        PyObject *pymods, *args, *pyfunc1, *pyfunc2;
        dict = PyDict_New();

        rc = PyRun_SimpleString(szCmd);
        if (rc == 0 && DEBUG)
            printf(" * DEBUG: Command : -->\n%s\n<-- end Command\n\n", szCmd);

        pytmp1 = PyString_FromString(szName);
        pymods = PyImport_Import(pytmp1);
        if (!pymods) {
            printf(" * ERROR: import module\n");
            break;
        }

        pyfunc1 = PyObject_GetAttrString(pymods, "conv");
        rc = PyCallable_Check(pyfunc1);
        if (!rc) {
            printf(" * ERROR: get function conv\n");
            break;
        }
        if (DEBUG)
            printf(" * DEBUG: get function conv\n");

        pyfunc2 = PyObject_GetAttrString(pymods, "run");
        rc = PyCallable_Check(pyfunc2);
        if (!rc) {
            printf(" * ERROR: get function run\n");
            break;
        }
        if (DEBUG)
            printf(" * DEBUG: get function run\n");

        args = PyTuple_New(argc - 1 - DEBUG);
        for (i = DEBUG + 1; i < argc; i++) {
            pytmp1 = PyString_FromString(argv[i]);
            PyTuple_SetItem(args, i - DEBUG - 1, pytmp1);
        }

        color("B", "(begin ----------------------------------------");
        ret = PyObject_CallObject(pyfunc1, args);
        if (ret) {
            cstr = PyString_AsString(ret);
        } else {
            color("R", "conv return NULL");
        }

//        args = PyTuple_New(0);
//        ret = PyObject_CallObject(pyfunc2, args);
//        color("B", cstr);
//        if (ret) {
//            rc = PyInt_AsLong(ret);
//        } else {
//            rc = -99;
//        }
        rc = system(cstr);
        color("B", cstr);

        if (rc == 0) {
            colori("G", rc);
        } else {
            colori("R", rc);
        }
        color("B", " end)");
    } while (0);

    Py_Finalize();

    if (DEBUG)
        printf(" * DEBUG: PyRun return code: %d\n", rc);
    return rc;
}

编译
f:\ux\mingw\bin\gcc -Wall -o c_call_py.exe c_call_py.c -I f:\ux\python26\include -L f:\ux\python26\Libs -lpython26
copy  c_call_py.exe cl.exe
copy  c_call_py.exe link.exe
copy  c_call_py.exe gcc.exe
copy  c_call_py.exe g++.exe


cl 参数转 gcc 参数
import os, sys

gccpath = r'f:\ux\mingw\bin'
pg = gccpath + '\gcc' #os.path.splitext( os.path.basename(sys.argv[0]) )[0]
cmd = ''

ENV = ['-I "%s"' % i for i in os.environ['INCLUDE'].split(';') if i != '']

def chkpar(i):
    if i in ['-Zi', '/Zi']: i = '-g'
    elif i.startswith('-D') or i.startswith('/D') and len(i) > 2: i = '-D%s' % i[2:]
    elif i.startswith('-W') or i.startswith('/W') and len(i) > 2: i = '-Wall'
    elif i in ['-Od', '/Od']: i = '-O0'
    if i not in ['-Zi', '-Od', '-MD', '-MT'] and i[-3:] != '.py':
        pass
    else:
        i = '   '
    return i

def conv(*args):
    global cmd
    par = []
    oricmd = []
    for i in args:
        if ' ' in i or '\t' in i or '\n' in i or '\r' in i:
            par.append('"%s"' % i)
            oricmd.append('"%s"' % i)
        else:
            par.append(chkpar(i))
            oricmd.append(i)

    cmd = '%s  %s %s' % (pg, ' '.join(par), ' '.join(ENV))
    return cmd

def run():
    global cmd
    return os.system(cmd)

def pr(*args):
    print args
    return 0

def main():
    os.system = pr
    global cmd
    cmd2 = conv(*sys.argv[1:])
    os.system('color2 B (begin ----------------------------------------')
    rc = run()
    os.system('color2 B %s' % cmd2)
    if rc != 0:
        os.system('color2 R %d end)' % rc)
    else:
        os.system('color2 G %d end)' % rc)

    return rc


if __name__ == '__main__':
    sys.exit(main())

link 参数转 gcc 参数
import os, sys

gccpath = r'f:\ux\mingw\bin'
pg = gccpath + '\gcc' #os.path.splitext( os.path.basename(sys.argv[0]) )[0]
cmd = ''

ENV = ['-L "%s"' % i for i in os.environ['LIB'].split(';') if i != '']

def chkpar(i):
    if i[-4:].find('.py') == -1:
        if i[:4] == '-def':
            i = '   '
        elif i == '-debug':
            i = '-g'
        elif i == '-release':
            i = '-O'
        elif i[-4:] == '.lib':
            i = '-l %s' % i[:-4]
        elif i[:5] == '-out:':
            i = '-o %s' % i[5:]
        elif i[-4:] == '.obj':
            i = i[:-2]
        elif i == '-dll':
            i = '-shared'
    return i

def conv(*args):
    global cmd
    par = []
    oricmd = []
    for i in args:
        if ' ' in i or '\t' in i or '\n' in i or '\r' in i:
            par.append('"%s"' % i)
            oricmd.append('"%s"' % i)
        else:
            par.append(chkpar(i))
            oricmd.append(i)

    cmd = '%s  %s %s' % (pg, ' '.join(par), ' '.join(ENV))
    return cmd

def run():
    global cmd
    return os.system(cmd)

def pr(*args):
    print args
    return 0

def main():
    os.system = pr
    global cmd
    cmd2 = conv(*sys.argv[1:])
    os.system('color2 B (begin ----------------------------------------')
    rc = run()
    os.system('color2 B %s' % cmd2)
    if rc != 0:
        os.system('color2 R %d end)' % rc)
    else:
        os.system('color2 G %d end)' % rc)

    return rc


if __name__ == '__main__':
    sys.exit(main())


创建一个程序的包装器,实现对调用程序的参数转换等功能,使用 c 源码生成 一个exe程序,与需要被包装的程序同名,程序目录在PATH中的位置比需要被包装的程序目录前面,  提供一个同名的py源文件,  实现 conv函数,输入类型任意个字符参数,输出字符串。

实现原理,外部程序执行包装程序,程序启动、初始化内嵌 py 环境、执行 sys.path 设置、加载同名 py 源程序、传递所有参数调用 conv 函数、返回实际程序名及修改过的参数、执行、返回执行结果、使用不同颜色文本显示执行结果







阅读(1639) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~