vs实现python c扩展模块

官方示例spam.cpp:

#include <Python.h>
static PyObject *
spam_system(PyObject *self, PyObject *args)
{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return Py_BuildValue("i", sts);
}

static PyMethodDef SpamMethods[] = {
    {"system",  spam_system, METH_VARARGS,"Execute a shell command."},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
initspam(void)
{
    (void) Py_InitModule("spam", SpamMethods);
}

1:添加包含头文件以及动态链接库目录

Debug模式下编译提示:

1>LINK : fatal error LNK1104: 无法打开文件“python27_d.lib”

pyconfig.h 文件部分内容如下:

# ifdef _DEBUG 
# pragma comment(lib,"python27_d.lib") 
# else 
# pragma comment(lib,"python27.lib") 
# endif /* _DEBUG */ 

默认python27_d.lib不存在,所以编译时候选择Release模式,编译成功后将目录下spam.dll改为python识别的pyd后缀。

测试test.py:

import spam

print dir(spam)
a = spam.system('echo hello ')

原文地址:https://www.cnblogs.com/persuit/p/6379140.html